diff --git a/.circleci/config.yml b/.circleci/config.yml index e5bc82a5967..e171759f1c4 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1255,7 +1255,15 @@ jobs: ls # Add --timeout to kill hanging tests after 120s (2 min) # Add --durations=20 to show 20 slowest tests for debugging - python -m pytest -vv tests/llm_translation --cov=litellm --cov-report=xml -v --junitxml=test-results/junit.xml --durations=20 -n 4 --timeout=120 --timeout_method=thread + # Subdirectories with dedicated jobs (maintain this list as new jobs are added) + IGNORE_DIRS=( + "tests/llm_translation/realtime" + ) + IGNORE_ARGS="" + for dir in "${IGNORE_DIRS[@]}"; do + IGNORE_ARGS="$IGNORE_ARGS --ignore=$dir" + done + python -m pytest -vv tests/llm_translation $IGNORE_ARGS --cov=litellm --cov-report=xml -v --junitxml=test-results/junit.xml --durations=20 -n 4 --timeout=120 --timeout_method=thread no_output_timeout: 120m - run: name: Rename the coverage files @@ -1271,6 +1279,54 @@ jobs: paths: - llm_translation_coverage.xml - llm_translation_coverage + realtime_translation_testing: + docker: + - image: cimg/python:3.11 + auth: + username: ${DOCKERHUB_USERNAME} + password: ${DOCKERHUB_PASSWORD} + working_directory: ~/project + + steps: + - checkout + - setup_google_dns + - run: + name: Install Dependencies + command: | + python -m pip install --upgrade pip + python -m pip install -r requirements.txt + pip install "pytest==7.3.1" + pip install "pytest-retry==1.6.3" + pip install "pytest-cov==5.0.0" + pip install "pytest-asyncio==0.21.1" + pip install "respx==0.22.0" + pip install "pytest-xdist==3.6.1" + pip install "pytest-timeout==2.2.0" + pip install "websockets" + # Run pytest and generate JUnit XML report + - run: + name: Run realtime tests + command: | + pwd + ls + # Add --timeout to kill hanging tests after 120s (2 min) + # Add --durations=20 to show 20 slowest tests for debugging + python -m pytest -vv tests/llm_translation/realtime --cov=litellm --cov-report=xml -v --junitxml=test-results/junit.xml --durations=20 -n 4 --timeout=120 --timeout_method=thread + no_output_timeout: 120m + - run: + name: Rename the coverage files + command: | + mv coverage.xml realtime_translation_coverage.xml + mv .coverage realtime_translation_coverage + + # Store test results + - store_test_results: + path: test-results + - persist_to_workspace: + root: . + paths: + - realtime_translation_coverage.xml + - realtime_translation_coverage mcp_testing: docker: - image: cimg/python:3.11 @@ -1316,6 +1372,51 @@ jobs: paths: - mcp_coverage.xml - mcp_coverage + agent_testing: + docker: + - image: cimg/python:3.11 + auth: + username: ${DOCKERHUB_USERNAME} + password: ${DOCKERHUB_PASSWORD} + working_directory: ~/project + + steps: + - checkout + - setup_google_dns + - run: + name: Install Dependencies + command: | + python -m pip install --upgrade pip + python -m pip install -r requirements.txt + pip install "pytest==7.3.1" + pip install "pytest-retry==1.6.3" + pip install "pytest-cov==5.0.0" + pip install "pytest-asyncio==0.21.1" + pip install "respx==0.22.0" + pip install "pydantic==2.11.0" + pip install "a2a-sdk" + # Run pytest and generate JUnit XML report + - run: + name: Run tests + command: | + pwd + ls + python -m pytest -vv tests/agent_tests --ignore=tests/agent_tests/local_only_agent_tests --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit.xml --durations=5 + no_output_timeout: 120m + - run: + name: Rename the coverage files + command: | + mv coverage.xml agent_coverage.xml + mv .coverage agent_coverage + + # Store test results + - store_test_results: + path: test-results + - persist_to_workspace: + root: . + paths: + - agent_coverage.xml + - agent_coverage guardrails_testing: docker: - image: cimg/python:3.11 @@ -3532,7 +3633,7 @@ jobs: python -m venv venv . venv/bin/activate pip install coverage - coverage combine llm_translation_coverage llm_responses_api_coverage ocr_coverage search_coverage mcp_coverage logging_coverage audio_coverage litellm_router_coverage litellm_router_unit_coverage local_testing_part1_coverage local_testing_part2_coverage litellm_assistants_api_coverage auth_ui_unit_tests_coverage langfuse_coverage caching_coverage litellm_proxy_unit_tests_part1_coverage litellm_proxy_unit_tests_part2_coverage image_gen_coverage pass_through_unit_tests_coverage batches_coverage litellm_security_tests_coverage guardrails_coverage litellm_mapped_tests_coverage + coverage combine llm_translation_coverage realtime_translation_coverage llm_responses_api_coverage ocr_coverage search_coverage mcp_coverage logging_coverage audio_coverage litellm_router_coverage litellm_router_unit_coverage local_testing_part1_coverage local_testing_part2_coverage litellm_assistants_api_coverage auth_ui_unit_tests_coverage langfuse_coverage caching_coverage litellm_proxy_unit_tests_part1_coverage litellm_proxy_unit_tests_part2_coverage image_gen_coverage pass_through_unit_tests_coverage batches_coverage litellm_security_tests_coverage guardrails_coverage litellm_mapped_tests_coverage coverage xml - codecov/upload: file: ./coverage.xml @@ -3754,6 +3855,9 @@ jobs: cd ui/litellm-dashboard + # Remove node_modules and package-lock to ensure clean install (fixes dependency resolution issues) + rm -rf node_modules package-lock.json + # Install dependencies first npm install @@ -4193,12 +4297,24 @@ workflows: only: - main - /litellm_.*/ + - realtime_translation_testing: + filters: + branches: + only: + - main + - /litellm_.*/ - mcp_testing: filters: branches: only: - main - /litellm_.*/ + - agent_testing: + filters: + branches: + only: + - main + - /litellm_.*/ - guardrails_testing: filters: branches: @@ -4304,7 +4420,9 @@ workflows: - upload-coverage: requires: - llm_translation_testing + - realtime_translation_testing - mcp_testing + - agent_testing - google_generate_content_endpoint_testing - guardrails_testing - llm_responses_api_testing @@ -4381,7 +4499,9 @@ workflows: - e2e_openai_endpoints - test_bad_database_url - llm_translation_testing + - realtime_translation_testing - mcp_testing + - agent_testing - google_generate_content_endpoint_testing - llm_responses_api_testing - ocr_testing diff --git a/CLAUDE.md b/CLAUDE.md index 23a0e97eaee..3cb67908076 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -90,6 +90,7 @@ LiteLLM is a unified interface for 100+ LLM providers with two main components: - Pydantic v2 for data validation - Async/await patterns throughout - Type hints required for all public APIs +- **Avoid imports within methods** — place all imports at the top of the file (module-level). Inline imports inside functions/methods make dependencies harder to trace and hurt readability. The only exception is avoiding circular imports where absolutely necessary. ### Testing Strategy - Unit tests in `tests/test_litellm/` diff --git a/Makefile b/Makefile index 0da83c363cd..b867d7ea35e 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,10 @@ # LiteLLM Makefile # Simple Makefile for running tests and basic development tasks -.PHONY: help test test-unit test-integration test-unit-helm lint format install-dev install-proxy-dev install-test-deps install-helm-unittest check-circular-imports check-import-safety +.PHONY: help test test-unit test-integration test-unit-helm \ + info lint lint-dev format \ + install-dev install-proxy-dev install-test-deps \ + install-helm-unittest check-circular-imports check-import-safety # Default target help: @@ -25,6 +28,13 @@ help: @echo " make test-integration - Run integration tests" @echo " make test-unit-helm - Run helm unit tests" +# Keep PIP simple for edge cases: +PIP := $(shell command -v pip > /dev/null 2>&1 && echo "pip" || echo "python3 -m pip") + +# Show info +info: + @echo "PIP: $(PIP)" + # Installation targets install-dev: poetry install --with dev @@ -34,19 +44,19 @@ install-proxy-dev: # CI-compatible installations (matches GitHub workflows exactly) install-dev-ci: - pip install openai==2.8.0 + $(PIP) install openai==2.8.0 poetry install --with dev - pip install openai==2.8.0 + $(PIP) install openai==2.8.0 install-proxy-dev-ci: poetry install --with dev,proxy-dev --extras proxy - pip install openai==2.8.0 + $(PIP) install openai==2.8.0 install-test-deps: install-proxy-dev - poetry run pip install "pytest-retry==1.6.3" - poetry run pip install pytest-xdist - poetry run pip install openapi-core - cd enterprise && poetry run pip install -e . && cd .. + poetry run $(PIP) install "pytest-retry==1.6.3" + poetry run $(PIP) install pytest-xdist + poetry run $(PIP) install openapi-core + cd enterprise && poetry run $(PIP) install -e . && cd .. install-helm-unittest: helm plugin install https://github.com/helm-unittest/helm-unittest --version v0.4.4 || echo "ignore error if plugin exists" @@ -62,8 +72,40 @@ format-check: install-dev lint-ruff: install-dev cd litellm && poetry run ruff check . && cd .. +# faster linter for developing ... +# inspiration from: +# https://github.com/astral-sh/ruff/discussions/10977 +# https://github.com/astral-sh/ruff/discussions/4049 +lint-format-changed: install-dev + @git diff origin/main --unified=0 --no-color -- '*.py' | \ + perl -ne '\ + if (/^diff --git a\/(.*) b\//) { $$file = $$1; } \ + if (/^@@ .* \+(\d+)(?:,(\d+))? @@/) { \ + $$start = $$1; $$count = $$2 || 1; $$end = $$start + $$count - 1; \ + print "$$file:$$start:1-$$end:999\n"; \ + }' | \ + while read range; do \ + file="$${range%%:*}"; \ + lines="$${range#*:}"; \ + echo "Formatting $$file (lines $$lines)"; \ + poetry run ruff format --range "$$lines" "$$file"; \ + done + +lint-ruff-dev: install-dev + @tmpfile=$$(mktemp /tmp/ruff-dev.XXXXXX) && \ + cd litellm && \ + (poetry run ruff check . --output-format=pylint || true) > "$$tmpfile" && \ + poetry run diff-quality --violations=pylint "$$tmpfile" --compare-branch=origin/main && \ + cd .. ; \ + rm -f "$$tmpfile" + +lint-ruff-FULL-dev: install-dev + @files=$$(git diff --name-only origin/main -- '*.py'); \ + if [ -n "$$files" ]; then echo "$$files" | xargs poetry run ruff check; \ + else echo "No changed .py files to check."; fi + lint-mypy: install-dev - poetry run pip install types-requests types-setuptools types-redis types-PyYAML + poetry run $(PIP) install types-requests types-setuptools types-redis types-PyYAML cd litellm && poetry run mypy . --ignore-missing-imports && cd .. lint-black: format-check @@ -72,11 +114,14 @@ check-circular-imports: install-dev cd litellm && poetry run python ../tests/documentation_tests/test_circular_imports.py && cd .. check-import-safety: install-dev - poetry run python -c "from litellm import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1) + @poetry run python -c "from litellm import *; print('[from litellm import *] OK! no issues!');" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1) # Combined linting (matches test-linting.yml workflow) lint: format-check lint-ruff lint-mypy check-circular-imports check-import-safety +# Faster linting for local development (only checks changed code) +lint-dev: lint-format-changed lint-mypy check-circular-imports check-import-safety + # Testing targets test: poetry run pytest tests/ diff --git a/ci_cd/security_scans.sh b/ci_cd/security_scans.sh index 3a212a56f64..340f8e96063 100755 --- a/ci_cd/security_scans.sh +++ b/ci_cd/security_scans.sh @@ -154,6 +154,7 @@ run_grype_scans() { "CVE-2025-15367" # No fix available yet "CVE-2025-12781" # No fix available yet "CVE-2025-11468" # No fix available yet + "CVE-2026-1299" # Python 3.13 email module header injection - not applicable, LiteLLM doesn't use BytesGenerator for email serialization ) # Build JSON array of allowlisted CVE IDs for jq diff --git a/cookbook/livekit_agent_sdk/README.md b/cookbook/livekit_agent_sdk/README.md new file mode 100644 index 00000000000..1c3f0bf9564 --- /dev/null +++ b/cookbook/livekit_agent_sdk/README.md @@ -0,0 +1,114 @@ +# LiveKit Voice Agent with LiteLLM Gateway + +Simple example showing how to use LiveKit's xAI realtime plugin with LiteLLM as a proxy. This lets you switch between xAI, OpenAI, and Azure realtime APIs without changing your code. + +## Quick Start + +### 1. Install dependencies + +```bash +pip install livekit-agents[xai] websockets +``` + +### 2. Start LiteLLM proxy + +```bash +# With xAI +export XAI_API_KEY="your-xai-key" +litellm --config config.yaml --port 4000 +``` + +### 3. Run the voice agent + +```bash +python main.py +``` + +Type your message and get a voice response from Grok! + +## Configuration + +Set these environment variables if needed: + +```bash +export LITELLM_PROXY_URL="http://localhost:4000" +export LITELLM_API_KEY="sk-1234" +export LITELLM_MODEL="grok-voice-agent" +``` + +Or use the defaults - connects to `http://localhost:4000` by default. + +## Example Config File + +Create a `config.yaml` with your realtime models: + +```yaml +model_list: + - model_name: grok-voice-agent + litellm_params: + model: xai/grok-2-vision-1212 + api_key: os.environ/XAI_API_KEY + model_info: + mode: realtime + + - model_name: openai-voice-agent + litellm_params: + model: gpt-4o-realtime-preview + api_key: os.environ/OPENAI_API_KEY + model_info: + mode: realtime + +general_settings: + master_key: sk-1234 +``` + +Then start: `litellm --config config.yaml --port 4000` + +## How It Works + +LiveKit's xAI plugin connects through LiteLLM proxy by setting `base_url`: + +```python +from livekit.plugins import xai + +model = xai.realtime.RealtimeModel( + voice="ara", + api_key="sk-1234", # LiteLLM proxy key + base_url="http://localhost:4000", # Point to LiteLLM +) +``` + +## Switching Providers + +Just change the model in your config - no code changes needed: + +**xAI Grok:** +```yaml +model: xai/grok-2-vision-1212 +``` + +**OpenAI:** +```yaml +model: gpt-4o-realtime-preview +``` + +**Azure OpenAI:** +```yaml +model: azure/gpt-4o-realtime-preview +api_base: https://your-endpoint.openai.azure.com/ +``` + +## Why Use LiteLLM? + +- ✅ **Switch providers** without changing agent code +- ✅ **Cost tracking** across all voice sessions +- ✅ **Rate limiting** and budgets +- ✅ **Load balancing** across multiple API keys +- ✅ **Fallbacks** to backup models + +## Learn More + +- [LiveKit xAI Realtime Tutorial](/docs/tutorials/livekit_xai_realtime) +- [xAI Realtime Docs](/docs/providers/xai_realtime) +- [LiveKit Agents Documentation](https://docs.livekit.io/agents/) +- [LiteLLM Realtime API](/docs/realtime) diff --git a/cookbook/livekit_agent_sdk/config.example.yaml b/cookbook/livekit_agent_sdk/config.example.yaml new file mode 100644 index 00000000000..1361f36af34 --- /dev/null +++ b/cookbook/livekit_agent_sdk/config.example.yaml @@ -0,0 +1,21 @@ +model_list: + - model_name: grok-voice-agent + litellm_params: + model: xai/grok-2-vision-1212 + api_key: os.environ/XAI_API_KEY + model_info: + mode: realtime + + - model_name: openai-voice-agent + litellm_params: + model: gpt-4o-realtime-preview + api_key: os.environ/OPENAI_API_KEY + model_info: + mode: realtime + +litellm_settings: + drop_params: True + telemetry: False + +general_settings: + master_key: sk-1234 # Change this to a secure key diff --git a/cookbook/livekit_agent_sdk/main.py b/cookbook/livekit_agent_sdk/main.py new file mode 100644 index 00000000000..0e2d7ebdfaf --- /dev/null +++ b/cookbook/livekit_agent_sdk/main.py @@ -0,0 +1,112 @@ +""" +Simple xAI Voice Agent using LiveKit SDK with LiteLLM Gateway + +This example shows how to use LiveKit's xAI realtime plugin through LiteLLM proxy. +LiteLLM acts as a unified interface, allowing you to switch between xAI, OpenAI, +and Azure realtime APIs without changing your agent code. +""" +import asyncio +import json +import os +import websockets + +# Configuration +PROXY_URL = os.getenv("LITELLM_PROXY_URL", "http://localhost:4000") +API_KEY = os.getenv("LITELLM_API_KEY", "sk-1234") +MODEL = os.getenv("LITELLM_MODEL", "grok-voice-agent") + + +async def run_voice_agent(): + """ + Simple voice agent that: + 1. Connects to xAI realtime API through LiteLLM proxy + 2. Sends a user message + 3. Streams back the response + """ + + url = f"ws://{PROXY_URL.replace('http://', '').replace('https://', '')}/v1/realtime?model={MODEL}" + headers = {"Authorization": f"Bearer {API_KEY}"} + + print(f"🎙️ Connecting to voice agent...") + print(f" Model: {MODEL}") + print(f" Proxy: {PROXY_URL}") + print() + + async with websockets.connect(url, additional_headers=headers) as ws: + # Receive initial connection event + initial = json.loads(await ws.recv()) + print(f"✅ Connected! Event: {initial['type']}\n") + + # Get user input + user_message = input("💬 Your message: ").strip() + if not user_message: + user_message = "Tell me a fun fact about AI!" + + print(f"\n🤖 Sending to {MODEL}...\n") + + # Send user message + await ws.send(json.dumps({ + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": user_message}] + } + })) + + # Request response + await ws.send(json.dumps({ + "type": "response.create", + "response": {"modalities": ["text", "audio"]} + })) + + # Stream response + print("🎤 Response: ", end='', flush=True) + transcript = [] + + try: + while True: + msg = await asyncio.wait_for(ws.recv(), timeout=15.0) + event = json.loads(msg) + + # Capture transcript deltas + if event['type'] == 'response.output_audio_transcript.delta': + delta = event.get('delta', '') + if delta: + print(delta, end='', flush=True) + transcript.append(delta) + + # Done when response completes + elif event['type'] == 'response.done': + break + + except asyncio.TimeoutError: + pass + + print("\n") + + if transcript: + print(f"✅ Complete response: {''.join(transcript)}") + + await ws.close() + + +def main(): + """Run the voice agent""" + print("=" * 70) + print("LiveKit xAI Voice Agent via LiteLLM Proxy") + print("=" * 70) + print() + + try: + asyncio.run(run_voice_agent()) + except KeyboardInterrupt: + print("\n\n👋 Goodbye!") + except Exception as e: + print(f"\n❌ Error: {e}") + print("\nMake sure LiteLLM proxy is running:") + print(f" litellm --config config.yaml --port 4000") + + +if __name__ == "__main__": + main() diff --git a/cookbook/livekit_agent_sdk/requirements.txt b/cookbook/livekit_agent_sdk/requirements.txt new file mode 100644 index 00000000000..9e3542fac27 --- /dev/null +++ b/cookbook/livekit_agent_sdk/requirements.txt @@ -0,0 +1,2 @@ +livekit-agents[xai]>=1.3.12 +websockets>=15.0.1 diff --git a/cookbook/nova_sonic_realtime.py b/cookbook/nova_sonic_realtime.py new file mode 100644 index 00000000000..0ea0badfb01 --- /dev/null +++ b/cookbook/nova_sonic_realtime.py @@ -0,0 +1,284 @@ +""" +Client script to test Nova Sonic realtime API through LiteLLM proxy. + +This script connects to LiteLLM proxy's realtime endpoint and enables +speech-to-speech conversation with Bedrock Nova Sonic. + +Prerequisites: +- LiteLLM proxy running with Bedrock configured +- pyaudio installed: pip install pyaudio +- websockets installed: pip install websockets + +Usage: + python nova_sonic_realtime.py +""" + +import asyncio +import base64 +import json +import pyaudio +import websockets +from typing import Optional + +# Audio configuration (matching Nova Sonic requirements) +INPUT_SAMPLE_RATE = 16000 # Nova Sonic expects 16kHz input +OUTPUT_SAMPLE_RATE = 24000 # Nova Sonic outputs 24kHz +CHANNELS = 1 +FORMAT = pyaudio.paInt16 +CHUNK_SIZE = 1024 + +# LiteLLM proxy configuration +LITELLM_PROXY_URL = "ws://localhost:4000/v1/realtime?model=bedrock-sonic" +LITELLM_API_KEY = "sk-12345" # Your LiteLLM API key + + +class RealtimeClient: + """Client for LiteLLM realtime API with audio support.""" + + def __init__(self, url: str, api_key: str): + self.url = url + self.api_key = api_key + self.ws: Optional[websockets.WebSocketClientProtocol] = None + self.is_active = False + self.audio_queue = asyncio.Queue() + self.pyaudio = pyaudio.PyAudio() + self.input_stream = None + self.output_stream = None + + async def connect(self): + """Connect to LiteLLM proxy realtime endpoint.""" + print(f"Connecting to {self.url}...") + + headers = {} + if self.api_key: + headers["Authorization"] = f"Bearer {self.api_key}" + + self.ws = await websockets.connect( + self.url, + additional_headers=headers, + max_size=10 * 1024 * 1024, # 10MB max message size + ) + self.is_active = True + print("✓ Connected to LiteLLM proxy") + + async def send_session_update(self): + """Send session configuration.""" + session_update = { + "type": "session.update", + "session": { + "instructions": "You are a friendly assistant. Keep your responses short and conversational.", + "voice": "matthew", + "temperature": 0.8, + "max_response_output_tokens": 1024, + "modalities": ["text", "audio"], + "input_audio_format": "pcm16", + "output_audio_format": "pcm16", + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 500, + }, + }, + } + await self.ws.send(json.dumps(session_update)) + print("✓ Session configuration sent") + + async def receive_messages(self): + """Receive and process messages from the server.""" + try: + async for message in self.ws: + if not self.is_active: + break + + try: + data = json.loads(message) + event_type = data.get("type") + + if event_type == "session.created": + print(f"✓ Session created: {data.get('session', {}).get('id')}") + + elif event_type == "response.created": + print("🤖 Assistant is responding...") + + elif event_type == "response.text.delta": + # Print text transcription + delta = data.get("delta", "") + print(delta, end="", flush=True) + + elif event_type == "response.audio.delta": + # Queue audio for playback + audio_b64 = data.get("delta", "") + if audio_b64: + audio_bytes = base64.b64decode(audio_b64) + await self.audio_queue.put(audio_bytes) + + elif event_type == "response.text.done": + print() # New line after text + + elif event_type == "response.done": + print("✓ Response complete") + + elif event_type == "error": + print(f"❌ Error: {data.get('error', {})}") + + else: + # Debug: print other event types + print(f"[{event_type}]", end=" ") + + except json.JSONDecodeError: + print(f"Failed to parse message: {message[:100]}") + + except websockets.exceptions.ConnectionClosed: + print("\n✗ Connection closed") + except Exception as e: + print(f"\n✗ Error receiving messages: {e}") + finally: + self.is_active = False + + async def send_audio_chunk(self, audio_bytes: bytes): + """Send audio chunk to server.""" + if not self.is_active or not self.ws: + return + + audio_b64 = base64.b64encode(audio_bytes).decode("utf-8") + message = { + "type": "input_audio_buffer.append", + "audio": audio_b64, + } + await self.ws.send(json.dumps(message)) + + async def commit_audio_buffer(self): + """Commit the audio buffer to trigger processing.""" + if not self.is_active or not self.ws: + return + + message = {"type": "input_audio_buffer.commit"} + await self.ws.send(json.dumps(message)) + + async def capture_audio(self): + """Capture audio from microphone and send to server.""" + print("\n🎤 Starting audio capture...") + print("Speak into your microphone. Press Ctrl+C to stop.\n") + + self.input_stream = self.pyaudio.open( + format=FORMAT, + channels=CHANNELS, + rate=INPUT_SAMPLE_RATE, + input=True, + frames_per_buffer=CHUNK_SIZE, + ) + + try: + while self.is_active: + audio_data = self.input_stream.read(CHUNK_SIZE, exception_on_overflow=False) + await self.send_audio_chunk(audio_data) + await asyncio.sleep(0.01) # Small delay to prevent overwhelming + except Exception as e: + print(f"Error capturing audio: {e}") + finally: + if self.input_stream: + self.input_stream.stop_stream() + self.input_stream.close() + + async def play_audio(self): + """Play audio responses from the server.""" + print("🔊 Starting audio playback...") + + self.output_stream = self.pyaudio.open( + format=FORMAT, + channels=CHANNELS, + rate=OUTPUT_SAMPLE_RATE, + output=True, + frames_per_buffer=CHUNK_SIZE, + ) + + try: + while self.is_active: + try: + audio_data = await asyncio.wait_for( + self.audio_queue.get(), timeout=0.1 + ) + if audio_data: + self.output_stream.write(audio_data) + except asyncio.TimeoutError: + continue + except Exception as e: + print(f"Error playing audio: {e}") + finally: + if self.output_stream: + self.output_stream.stop_stream() + self.output_stream.close() + + async def close(self): + """Close the connection and cleanup.""" + self.is_active = False + + if self.ws: + await self.ws.close() + + if self.input_stream: + self.input_stream.stop_stream() + self.input_stream.close() + + if self.output_stream: + self.output_stream.stop_stream() + self.output_stream.close() + + self.pyaudio.terminate() + print("\n✓ Connection closed") + + +async def main(): + """Main function to run the realtime client.""" + print("=" * 80) + print("Bedrock Nova Sonic Realtime Client") + print("=" * 80) + print() + + client = RealtimeClient(LITELLM_PROXY_URL, LITELLM_API_KEY) + + try: + # Connect to server + await client.connect() + + # Send session configuration + await client.send_session_update() + + # Wait a moment for session to be established + await asyncio.sleep(0.5) + + # Start tasks + receive_task = asyncio.create_task(client.receive_messages()) + capture_task = asyncio.create_task(client.capture_audio()) + playback_task = asyncio.create_task(client.play_audio()) + + # Wait for user to interrupt + await asyncio.gather( + receive_task, + capture_task, + playback_task, + return_exceptions=True, + ) + + except KeyboardInterrupt: + print("\n\n⚠ Interrupted by user") + except Exception as e: + print(f"\n❌ Error: {e}") + import traceback + traceback.print_exc() + finally: + await client.close() + + +if __name__ == "__main__": + print("\nMake sure:") + print("1. LiteLLM proxy is running on port 4000") + print("2. Bedrock is configured in proxy_server_config.yaml") + print("3. AWS credentials are set") + print() + + try: + asyncio.run(main()) + except KeyboardInterrupt: + print("\n\nGoodbye!") diff --git a/docker/Dockerfile.non_root b/docker/Dockerfile.non_root index 9ff27e07494..3ef47607fca 100644 --- a/docker/Dockerfile.non_root +++ b/docker/Dockerfile.non_root @@ -47,7 +47,6 @@ RUN mkdir -p /var/lib/litellm/ui && \ if [ -f "/app/enterprise/enterprise_ui/enterprise_colors.json" ]; then \ cp /app/enterprise/enterprise_ui/enterprise_colors.json ./ui_colors.json; \ fi && \ - rm -f package-lock.json && \ npm install --legacy-peer-deps && \ npm run build && \ cp -r /app/ui/litellm-dashboard/out/* /var/lib/litellm/ui/ && \ diff --git a/docs/my-website/blog/claude_opus_4_6/index.md b/docs/my-website/blog/claude_opus_4_6/index.md new file mode 100644 index 00000000000..0397f1288f7 --- /dev/null +++ b/docs/my-website/blog/claude_opus_4_6/index.md @@ -0,0 +1,403 @@ +--- +slug: claude_opus_4_6 +title: "Day 0 Support: Claude Opus 4.6" +date: 2026-02-05T10:00:00 +authors: + - name: Sameer Kankute + title: SWE @ LiteLLM (LLM Translation) + url: https://www.linkedin.com/in/sameer-kankute/ + image_url: https://pbs.twimg.com/profile_images/2001352686994907136/ONgNuSk5_400x400.jpg + - name: Ishaan Jaff + title: "CTO, LiteLLM" + url: https://www.linkedin.com/in/reffajnaahsi/ + image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg + - name: Krrish Dholakia + title: "CEO, LiteLLM" + url: https://www.linkedin.com/in/krish-d/ + image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg +description: "Day 0 support for Claude Opus 4.6 on LiteLLM AI Gateway - use across Anthropic, Azure, Vertex AI, and Bedrock." +tags: [anthropic, claude, opus 4.6] +hide_table_of_contents: false +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +LiteLLM now supports Claude Opus 4.6 on Day 0. Use it across Anthropic, Azure, Vertex AI, and Bedrock through the LiteLLM AI Gateway. + +## Docker Image + +```bash +docker pull ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 +``` + +## Usage - Anthropic + + + + +**1. Setup config.yaml** + +```yaml +model_list: + - model_name: claude-opus-4-6 + litellm_params: + model: anthropic/claude-opus-4-6 + api_key: os.environ/ANTHROPIC_API_KEY +``` + +**2. Start the proxy** + +```bash +docker run -d \ + -p 4000:4000 \ + -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \ + -v $(pwd)/config.yaml:/app/config.yaml \ + ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 \ + --config /app/config.yaml +``` + +**3. Test it!** + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer $LITELLM_KEY' \ +--data '{ + "model": "claude-opus-4-6", + "messages": [ + { + "role": "user", + "content": "what llm are you" + } + ] +}' +``` + + + + +## Usage - Azure + + + + +**1. Setup config.yaml** + +```yaml +model_list: + - model_name: claude-opus-4-6 + litellm_params: + model: azure_ai/claude-opus-4-6 + api_key: os.environ/AZURE_AI_API_KEY + api_base: os.environ/AZURE_AI_API_BASE # https://.services.ai.azure.com +``` + +**2. Start the proxy** + +```bash +docker run -d \ + -p 4000:4000 \ + -e AZURE_AI_API_KEY=$AZURE_AI_API_KEY \ + -e AZURE_AI_API_BASE=$AZURE_AI_API_BASE \ + -v $(pwd)/config.yaml:/app/config.yaml \ + ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 \ + --config /app/config.yaml +``` + +**3. Test it!** + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer $LITELLM_KEY' \ +--data '{ + "model": "claude-opus-4-6", + "messages": [ + { + "role": "user", + "content": "what llm are you" + } + ] +}' +``` + + + + +## Usage - Vertex AI + + + + +**1. Setup config.yaml** + +```yaml +model_list: + - model_name: claude-opus-4-6 + litellm_params: + model: vertex_ai/claude-opus-4-6 + vertex_project: os.environ/VERTEX_PROJECT + vertex_location: us-east5 +``` + +**2. Start the proxy** + +```bash +docker run -d \ + -p 4000:4000 \ + -e VERTEX_PROJECT=$VERTEX_PROJECT \ + -e GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json \ + -v $(pwd)/config.yaml:/app/config.yaml \ + -v $(pwd)/credentials.json:/app/credentials.json \ + ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 \ + --config /app/config.yaml +``` + +**3. Test it!** + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer $LITELLM_KEY' \ +--data '{ + "model": "claude-opus-4-6", + "messages": [ + { + "role": "user", + "content": "what llm are you" + } + ] +}' +``` + + + + +## Usage - Bedrock + + + + +**1. Setup config.yaml** + +```yaml +model_list: + - model_name: claude-opus-4-6 + litellm_params: + model: bedrock/anthropic.claude-opus-4-6-v1:0 + aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID + aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY + aws_region_name: us-east-1 +``` + +**2. Start the proxy** + +```bash +docker run -d \ + -p 4000:4000 \ + -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \ + -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \ + -v $(pwd)/config.yaml:/app/config.yaml \ + ghcr.io/berriai/litellm:litellm_stable_release_branch-v1.80.0-stable.opus-4-6 \ + --config /app/config.yaml +``` + +**3. Test it!** + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer $LITELLM_KEY' \ +--data '{ + "model": "claude-opus-4-6", + "messages": [ + { + "role": "user", + "content": "what llm are you" + } + ] +}' +``` + + + + +## Compaction + +Litellm supports enabling compaction for the new claude-opus-4-6. + +### Enabling Compaction + +To enable compaction, add the `context_management` parameter with the `compact_20260112` edit type: + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer $LITELLM_KEY' \ +--data '{ + "model": "claude-opus-4-6", + "messages": [ + { + "role": "user", + "content": "What is the weather in San Francisco?" + } + ], + "context_management": { + "edits": [ + { + "type": "compact_20260112" + } + ] + }, + "max_tokens": 100 +}' +``` +All the parameters supported for context_management by anthropic are supported and can be directly added. Litellm automatically adds the `compact-2026-01-12` beta header in the request. + + +### Response with Compaction Block + +The response will include the compaction summary in `provider_specific_fields.compaction_blocks`: + +```json +{ + "id": "chatcmpl-a6c105a3-4b25-419e-9551-c800633b6cb2", + "created": 1770357619, + "model": "claude-opus-4-6", + "object": "chat.completion", + "choices": [ + { + "finish_reason": "length", + "index": 0, + "message": { + "content": "I don't have access to real-time data, so I can't provide the current weather in San Francisco. To get up-to-date weather information, I'd recommend checking:\n\n- **Weather websites** like weather.com, accuweather.com, or wunderground.com\n- **Search engines** – just Google \"San Francisco weather\"\n- **Weather apps** on your phone (e.g., Apple Weather, Google Weather)\n- **National", + "role": "assistant", + "provider_specific_fields": { + "compaction_blocks": [ + { + "type": "compaction", + "content": "Summary of the conversation: The user requested help building a web scraper..." + } + ] + } + } + } + ], + "usage": { + "completion_tokens": 100, + "prompt_tokens": 86, + "total_tokens": 186 + } +} +``` + +### Using Compaction Blocks in Follow-up Requests + +To continue the conversation with compaction, include the compaction block in the assistant message's `provider_specific_fields`: + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer $LITELLM_KEY' \ +--data '{ + "model": "claude-opus-4-6", + "messages": [ + { + "role": "user", + "content": "How can I build a web scraper?" + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "Certainly! To build a basic web scraper, you'll typically use a programming language like Python along with libraries such as `requests` (for fetching web pages) and `BeautifulSoup` (for parsing HTML). Here's a basic example:\n\n```python\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://example.com'\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, 'html.parser')\n\n# Extract and print all text\ntext = soup.get_text()\nprint(text)\n```\n\nLet me know what you're interested in scraping or if you need help with a specific website!" + } + ], + "provider_specific_fields": { + "compaction_blocks": [ + { + "type": "compaction", + "content": "Summary of the conversation: The user asked how to build a web scraper, and the assistant gave an overview using Python with requests and BeautifulSoup." + } + ] + } + }, + { + "role": "user", + "content": "How do I use it to scrape product prices?" + } + ], + "context_management": { + "edits": [ + { + "type": "compact_20260112" + } + ] + }, + "max_tokens": 100 +}' +``` + +### Streaming Support + +Compaction blocks are also supported in streaming mode. You'll receive: +- `compaction_start` event when a compaction block begins +- `compaction_delta` events with the compaction content +- The accumulated `compaction_blocks` in `provider_specific_fields` + + +## Adaptive Thinking + +LiteLLM supports adaptive thinking through the `reasoning_effort` parameter: + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer $LITELLM_KEY' \ +--data '{ + "model": "claude-opus-4-6", + "messages": [ + { + "role": "user", + "content": "Solve this complex problem: What is the optimal strategy for..." + } + ], + "reasoning_effort": "high" +}' +``` + +## Effort Levels + +Four effort levels available: `low`, `medium`, `high` (default), and `max`. Pass directly via the `output_config` parameter: + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer $LITELLM_KEY' \ +--data '{ + "model": "claude-opus-4-6", + "messages": [ + { + "role": "user", + "content": "Explain quantum computing" + } + ], + "output_config": { + "effort": "medium" + } + +}' +``` + +You can use reasoning effort plus output_config to have more control on the model. + +## 1M Token Context (Beta) + +Opus 4.6 supports 1M token context. Premium pricing applies for prompts exceeding 200k tokens ($10/$37.50 per million input/output tokens). LiteLLM supports cost calculations for 1M token contexts. + +## US-Only Inference + +Available at 1.1× token pricing. LiteLLM supports this pricing model. + diff --git a/docs/my-website/blog/litellm_observatory/index.md b/docs/my-website/blog/litellm_observatory/index.md new file mode 100644 index 00000000000..f9944be8c27 --- /dev/null +++ b/docs/my-website/blog/litellm_observatory/index.md @@ -0,0 +1,136 @@ +--- +slug: litellm-observatory +title: "LiteLLM Observatory: Raising the Bar for Release Reliability" +date: 2026-02-06T10:00:00 +authors: + - name: Alexsander Hamir + title: "Performance Engineer, LiteLLM" + url: https://www.linkedin.com/in/alexsander-baptista/ + image_url: https://github.com/AlexsanderHamir.png + - name: Krrish Dholakia + title: "CEO, LiteLLM" + url: https://www.linkedin.com/in/krish-d/ + image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg + - name: Ishaan Jaff + title: "CTO, LiteLLM" + url: https://www.linkedin.com/in/reffajnaahsi/ + image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg +description: "How we built a long-running, release-validation system to catch regressions before they reach users." +tags: [testing, observability, reliability, releases] +hide_table_of_contents: false +--- + +![LiteLLM Observatory](https://raw.githubusercontent.com/AlexsanderHamir/assets/main/Screenshot%202026-01-31%20175355.png) + +# LiteLLM Observatory: Raising the Bar for Release Reliability + +As LiteLLM adoption has grown, so have expectations around reliability, performance, and operational safety. Meeting those expectations requires more than correctness-focused tests, it requires validating how the system behaves over time, under real-world conditions. + +This post introduces **LiteLLM Observatory**, a long-running release-validation system we built to catch regressions before they reach users. + +--- + +## Why We Built the Observatory + +LiteLLM operates at the intersection of external providers, long-lived network connections, and high-throughput workloads. While our unit and integration tests do an excellent job validating correctness, they are not designed to surface issues that only appear after extended operation. + +A subtle lifecycle edge case discovered in v1.81.3 reinforced the need for stronger release validation in this area. + +--- + +## A Real-World Lifecycle Edge Case + +In v1.81.3, we shipped a fix for an HTTP client memory leak. The change passed unit and integration tests and behaved correctly in short-lived runs. + +The issue that surfaced was not caused by a single incorrect line of logic, but by how multiple components interacted over time: + +- A cached `httpx` client was configured with a 1-hour TTL +- When the cache expired, the underlying HTTP connection was closed as expected +- A higher-level client continued to hold a reference to that connection +- Subsequent requests failed with: + +``` +Cannot send a request, as the client has been closed +``` + +Our focus moving forward is on being the first to detect issues, even when they aren’t covered by unit tests. LiteLLM Observatory is designed to surface latency regressions, OOMs, and failure modes that only appear under real traffic patterns in **our own production deployments** during release validation. + + +--- + +## Introducing LiteLLM Observatory + +To systematically address this class of issues, we built **LiteLLM Observatory**. + +The Observatory is a long-running testing orchestrator used during release validation to exercise LiteLLM under production-like conditions for extended periods of time. + +Its core goals are: + +- Validate behavior over hours, not minutes +- Turn production learnings into permanent release safeguards + +--- + +### How the Observatory Works + +[LiteLLM Observatory](https://github.com/BerriAI/litellm-observatory) is a testing service that runs long-running tests against our LiteLLM deployments. We trigger tests by sending API requests, and results are automatically sent to Slack when tests complete. + +#### How Tests Run + +1. **Start a Test**: We send a request to the Observatory API with: + - Which LiteLLM deployment to test (URL and API key) + - Which test to run (e.g., `TestOAIAzureRelease`) + - Test settings (which models to test, how long to run, failure thresholds) + +2. **Smart Queueing**: + - The system checks whether we are attempting to run the exact same test more than once + - If a duplicate test is already running or queued, we receive an error to avoid wasting resources + - Otherwise, the test is added to a queue and runs when capacity is available (up to 5 tests can run concurrently by default) + +3. **Instant Response**: The API responds immediately—we do not wait for the test to finish. Tests may run for hours, but the request itself completes in milliseconds. + +4. **Background Execution**: + - The test runs in the background, issuing requests against our LiteLLM deployment + - It tracks request success and failure rates over time + - When the test completes, results are automatically posted to our Slack channel + +#### Example: The OpenAI / Azure Reliability Test + +The `TestOAIAzureRelease` test is designed to catch a class of bugs that only surface after sustained runtime: + +- **Duration**: Runs continuously for 3 hours +- **Behavior**: Cycles through specified models (such as `gpt-4` and `gpt-3.5-turbo`), issuing requests continuously +- **Why 3 Hours**: This helps catch issues where HTTP clients degrade or fail after extended use (for example, a bug observed in LiteLLM v1.81.3) +- **Pass / Fail Criteria**: The test passes if fewer than 1% of requests fail. If the failure rate exceeds 1%, the test fails and we are notified in Slack +- **Key Detail**: The same HTTP client is reused for the entire run, allowing us to detect lifecycle-related bugs that only appear under prolonged reuse + +#### When We Use It + +- **Before Deployments**: Run tests before promoting a new LiteLLM version to production +- **Routine Validation**: Schedule regular runs (daily or weekly) to catch regressions early +- **Issue Investigation**: Run tests on demand when we suspect a deployment issue +- **Long-Running Failure Detection**: Identify bugs that only appear under sustained load, beyond what short smoke tests can reveal + + +### Complementing Unit Tests + +Unit tests remain a foundational part of our development process. They are fast and precise, but they don’t cover: + +- Real provider behavior +- Long-lived network interactions +- Resource lifecycle edge cases +- Time-dependent regressions + +LiteLLM Observatory complements unit tests by validating the system as it actually runs in production-like environments. + +--- + +### Looking Ahead + +Reliability is an ongoing investment. + +LiteLLM Observatory is one of several systems we’re building to continuously raise the bar on release quality and operational safety. As LiteLLM evolves, so will our validation tooling, informed by real-world usage and lessons learned. + +We’ll continue to share those improvements openly as we go. +``` + diff --git a/docs/my-website/blog/sub_millisecond_proxy_overhead/index.md b/docs/my-website/blog/sub_millisecond_proxy_overhead/index.md new file mode 100644 index 00000000000..1857383363c --- /dev/null +++ b/docs/my-website/blog/sub_millisecond_proxy_overhead/index.md @@ -0,0 +1,92 @@ +--- +slug: sub-millisecond-proxy-overhead +title: "Achieving Sub-Millisecond Proxy Overhead" +date: 2026-02-02T10:00:00 +authors: + - name: Alexsander Hamir + title: "Performance Engineer, LiteLLM" + url: https://www.linkedin.com/in/alexsander-baptista/ + image_url: https://github.com/AlexsanderHamir.png + - name: Krrish Dholakia + title: "CEO, LiteLLM" + url: https://www.linkedin.com/in/krish-d/ + image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg + - name: Ishaan Jaff + title: "CTO, LiteLLM" + url: https://www.linkedin.com/in/reffajnaahsi/ + image_url: https://pbs.twimg.com/profile_images/1613813310264340481/lz54oEiB_400x400.jpg +description: "Our Q1 performance target and architectural direction for achieving sub-millisecond proxy overhead on modest hardware." +tags: [performance, architecture] +hide_table_of_contents: false +--- + +![Sidecar architecture: Python control plane vs. sidecar hot path](https://raw.githubusercontent.com/AlexsanderHamir/assets/main/Screenshot%202026-02-02%20172554.png) + +# Achieving Sub-Millisecond Proxy Overhead + +## Introduction + +Our Q1 performance target is to aggressively move toward sub-millisecond proxy overhead on a single instance with 4 CPUs and 8 GB of RAM, and to continue pushing that boundary over time. Our broader goal is to make LiteLLM inexpensive to deploy, lightweight, and fast. This post outlines the architectural direction behind that effort. + +Proxy overhead refers to the latency introduced by LiteLLM itself, independent of the upstream provider. + +To measure it, we run the same workload directly against the provider and through LiteLLM at identical QPS (for example, 1,000 QPS) and compare the latency delta. To reduce noise, the load generator, LiteLLM, and a mock LLM endpoint all run on the same machine, ensuring the difference reflects proxy overhead rather than network latency. + +--- + +## Where We're Coming From + +Under the same benchmark originally conducted by [TensorZero](https://www.tensorzero.com/docs/gateway/benchmarks), LiteLLM previously failed at around 1,000 QPS. + +That is no longer the case. Today, LiteLLM can be stress-tested at 1,000 QPS with no failures and can scale up to 5,000 QPS without failures on a 4-CPU, 8-GB RAM single instance setup. + +This establishes a more up to date baseline and provides useful context as we continue working on proxy overhead and overall performance. + +--- + +## Design Choice + +Achieving sub-millisecond proxy overhead with a Python-based system requires being deliberate about where work happens. + +Python is a strong fit for flexibility and extensibility: provider abstraction, configuration-driven routing, and a rich callback ecosystem. These are areas where development velocity and correctness matter more than raw throughput. + +At higher request rates, however, certain classes of work become expensive when executed inside the Python process on every request. Rather than rewriting LiteLLM or introducing complex deployment requirements, we adopt an optional **sidecar architecture**. + +This architectural change is how we intend to make LiteLLM **permanently fast**. While it supports our near-term performance targets, it is a long-term investment. + +Python continues to own: + +- Request validation and normalization +- Model and provider selection +- Callbacks and integrations + +The sidecar owns **performance-critical execution**, such as: + +- Efficient request forwarding +- Connection reuse and pooling +- Enforcing timeouts and limits +- Aggregating high-frequency metrics + +This separation allows each component to focus on what it does best: Python acts as the control plane, while the sidecar handles the hot path. + +--- + +### Why the Sidecar Is Optional + +The sidecar is intentionally **optional**. + +This allows us to ship it incrementally, validate it under real-world workloads, and avoid making it a hard dependency before it is fully battle-tested across all LiteLLM features. + +Just as importantly, this ensures that self-hosting LiteLLM remains simple. The sidecar is bundled and started automatically, requires no additional infrastructure, and can be disabled entirely. From a user's perspective, LiteLLM continues to behave like a single service. + +As of today, the sidecar is an optimization, not a requirement. + +--- + +## Conclusion + +Sub-millisecond proxy overhead is not achieved through a single optimization, but through architectural changes. + +By keeping Python focused on orchestration and extensibility, and offloading performance-critical execution to a sidecar, we establish a foundation for making LiteLLM **permanently fast over time**—even on modest hardware such as a 1-CPU, 2-GB RAM instance, while keeping deployment and self-hosting simple. + +This work extends beyond Q1, and we will continue sharing benchmarks and updates as the architecture evolves. diff --git a/docs/my-website/docs/a2a.md b/docs/my-website/docs/a2a.md index a7e8b52d99a..b1166a7809c 100644 --- a/docs/my-website/docs/a2a.md +++ b/docs/my-website/docs/a2a.md @@ -68,116 +68,9 @@ Follow [this guide, to add your pydantic ai agent to LiteLLM Agent Gateway](./pr ## Invoking your Agents -Use the [A2A Python SDK](https://pypi.org/project/a2a-sdk) to invoke agents through LiteLLM. - -This example shows how to: -1. **List available agents** - Query `/v1/agents` to see which agents your key can access -2. **Select an agent** - Pick an agent from the list -3. **Invoke via A2A** - Use the A2A protocol to send messages to the agent - -```python showLineNumbers title="invoke_a2a_agent.py" -from uuid import uuid4 -import httpx -import asyncio -from a2a.client import A2ACardResolver, A2AClient -from a2a.types import MessageSendParams, SendMessageRequest - -# === CONFIGURE THESE === -LITELLM_BASE_URL = "http://localhost:4000" # Your LiteLLM proxy URL -LITELLM_VIRTUAL_KEY = "sk-1234" # Your LiteLLM Virtual Key -# ======================= - -async def main(): - headers = {"Authorization": f"Bearer {LITELLM_VIRTUAL_KEY}"} - - async with httpx.AsyncClient(headers=headers) as client: - # Step 1: List available agents - response = await client.get(f"{LITELLM_BASE_URL}/v1/agents") - agents = response.json() - - print("Available agents:") - for agent in agents: - print(f" - {agent['agent_name']} (ID: {agent['agent_id']})") - - if not agents: - print("No agents available for this key") - return - - # Step 2: Select an agent and invoke it - selected_agent = agents[0] - agent_id = selected_agent["agent_id"] - agent_name = selected_agent["agent_name"] - print(f"\nInvoking: {agent_name}") - - # Step 3: Use A2A protocol to invoke the agent - base_url = f"{LITELLM_BASE_URL}/a2a/{agent_id}" - resolver = A2ACardResolver(httpx_client=client, base_url=base_url) - agent_card = await resolver.get_agent_card() - a2a_client = A2AClient(httpx_client=client, agent_card=agent_card) - - request = SendMessageRequest( - id=str(uuid4()), - params=MessageSendParams( - message={ - "role": "user", - "parts": [{"kind": "text", "text": "Hello, what can you do?"}], - "messageId": uuid4().hex, - } - ), - ) - response = await a2a_client.send_message(request) - print(f"Response: {response.model_dump(mode='json', exclude_none=True, indent=4)}") - -if __name__ == "__main__": - asyncio.run(main()) -``` - -### Streaming Responses - -For streaming responses, use `send_message_streaming`: - -```python showLineNumbers title="invoke_a2a_agent_streaming.py" -from uuid import uuid4 -import httpx -import asyncio -from a2a.client import A2ACardResolver, A2AClient -from a2a.types import MessageSendParams, SendStreamingMessageRequest - -# === CONFIGURE THESE === -LITELLM_BASE_URL = "http://localhost:4000" # Your LiteLLM proxy URL -LITELLM_VIRTUAL_KEY = "sk-1234" # Your LiteLLM Virtual Key -LITELLM_AGENT_NAME = "ij-local" # Agent name registered in LiteLLM -# ======================= - -async def main(): - base_url = f"{LITELLM_BASE_URL}/a2a/{LITELLM_AGENT_NAME}" - headers = {"Authorization": f"Bearer {LITELLM_VIRTUAL_KEY}"} - - async with httpx.AsyncClient(headers=headers) as httpx_client: - # Resolve agent card and create client - resolver = A2ACardResolver(httpx_client=httpx_client, base_url=base_url) - agent_card = await resolver.get_agent_card() - client = A2AClient(httpx_client=httpx_client, agent_card=agent_card) - - # Send a streaming message - request = SendStreamingMessageRequest( - id=str(uuid4()), - params=MessageSendParams( - message={ - "role": "user", - "parts": [{"kind": "text", "text": "Hello, what can you do?"}], - "messageId": uuid4().hex, - } - ), - ) - - # Stream the response - async for chunk in client.send_message_streaming(request): - print(chunk.model_dump(mode="json", exclude_none=True)) - -if __name__ == "__main__": - asyncio.run(main()) -``` +See the [Invoking A2A Agents](./a2a_invoking_agents) guide to learn how to call your agents using: +- **A2A SDK** - Native A2A protocol with full support for tasks and artifacts +- **OpenAI SDK** - Familiar `/chat/completions` interface with `a2a/` model prefix ## Tracking Agent Logs diff --git a/docs/my-website/docs/a2a_invoking_agents.md b/docs/my-website/docs/a2a_invoking_agents.md new file mode 100644 index 00000000000..3bb248e4561 --- /dev/null +++ b/docs/my-website/docs/a2a_invoking_agents.md @@ -0,0 +1,280 @@ +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# Invoking A2A Agents + +Learn how to invoke A2A agents through LiteLLM using different methods. + +:::tip Deploy Your Own A2A Agent + +Want to test with your own agent? Deploy this template A2A agent powered by Google Gemini: + +[**shin-bot-litellm/a2a-gemini-agent**](https://github.com/shin-bot-litellm/a2a-gemini-agent) - Simple deployable A2A agent with streaming support + +::: + +## A2A SDK + +Use the [A2A Python SDK](https://pypi.org/project/a2a-sdk) to invoke agents through LiteLLM using the A2A protocol. + +### Non-Streaming + +This example shows how to: +1. **List available agents** - Query `/v1/agents` to see which agents your key can access +2. **Select an agent** - Pick an agent from the list +3. **Invoke via A2A** - Use the A2A protocol to send messages to the agent + +```python showLineNumbers title="invoke_a2a_agent.py" +from uuid import uuid4 +import httpx +import asyncio +from a2a.client import A2ACardResolver, A2AClient +from a2a.types import MessageSendParams, SendMessageRequest + +# === CONFIGURE THESE === +LITELLM_BASE_URL = "http://localhost:4000" # Your LiteLLM proxy URL +LITELLM_VIRTUAL_KEY = "sk-1234" # Your LiteLLM Virtual Key +# ======================= + +async def main(): + headers = {"Authorization": f"Bearer {LITELLM_VIRTUAL_KEY}"} + + async with httpx.AsyncClient(headers=headers) as client: + # Step 1: List available agents + response = await client.get(f"{LITELLM_BASE_URL}/v1/agents") + agents = response.json() + + print("Available agents:") + for agent in agents: + print(f" - {agent['agent_name']} (ID: {agent['agent_id']})") + + if not agents: + print("No agents available for this key") + return + + # Step 2: Select an agent and invoke it + selected_agent = agents[0] + agent_id = selected_agent["agent_id"] + agent_name = selected_agent["agent_name"] + print(f"\nInvoking: {agent_name}") + + # Step 3: Use A2A protocol to invoke the agent + base_url = f"{LITELLM_BASE_URL}/a2a/{agent_id}" + resolver = A2ACardResolver(httpx_client=client, base_url=base_url) + agent_card = await resolver.get_agent_card() + a2a_client = A2AClient(httpx_client=client, agent_card=agent_card) + + request = SendMessageRequest( + id=str(uuid4()), + params=MessageSendParams( + message={ + "role": "user", + "parts": [{"kind": "text", "text": "Hello, what can you do?"}], + "messageId": uuid4().hex, + } + ), + ) + response = await a2a_client.send_message(request) + print(f"Response: {response.model_dump(mode='json', exclude_none=True, indent=4)}") + +if __name__ == "__main__": + asyncio.run(main()) +``` + +### Streaming + +For streaming responses, use `send_message_streaming`: + +```python showLineNumbers title="invoke_a2a_agent_streaming.py" +from uuid import uuid4 +import httpx +import asyncio +from a2a.client import A2ACardResolver, A2AClient +from a2a.types import MessageSendParams, SendStreamingMessageRequest + +# === CONFIGURE THESE === +LITELLM_BASE_URL = "http://localhost:4000" # Your LiteLLM proxy URL +LITELLM_VIRTUAL_KEY = "sk-1234" # Your LiteLLM Virtual Key +LITELLM_AGENT_NAME = "ij-local" # Agent name registered in LiteLLM +# ======================= + +async def main(): + base_url = f"{LITELLM_BASE_URL}/a2a/{LITELLM_AGENT_NAME}" + headers = {"Authorization": f"Bearer {LITELLM_VIRTUAL_KEY}"} + + async with httpx.AsyncClient(headers=headers) as httpx_client: + # Resolve agent card and create client + resolver = A2ACardResolver(httpx_client=httpx_client, base_url=base_url) + agent_card = await resolver.get_agent_card() + client = A2AClient(httpx_client=httpx_client, agent_card=agent_card) + + # Send a streaming message + request = SendStreamingMessageRequest( + id=str(uuid4()), + params=MessageSendParams( + message={ + "role": "user", + "parts": [{"kind": "text", "text": "Tell me a long story"}], + "messageId": uuid4().hex, + } + ), + ) + + # Stream the response + async for chunk in client.send_message_streaming(request): + print(chunk.model_dump(mode="json", exclude_none=True)) + +if __name__ == "__main__": + asyncio.run(main()) +``` + +## /chat/completions API (OpenAI SDK) + +You can also invoke A2A agents using the familiar OpenAI SDK by using the `a2a/` model prefix. + +### Non-Streaming + + + + +```python showLineNumbers title="openai_non_streaming.py" +import openai + +client = openai.OpenAI( + api_key="sk-1234", # Your LiteLLM Virtual Key + base_url="http://localhost:4000" # Your LiteLLM proxy URL +) + +response = client.chat.completions.create( + model="a2a/my-agent", # Use a2a/ prefix with your agent name + messages=[ + {"role": "user", "content": "Hello, what can you do?"} + ] +) + +print(response.choices[0].message.content) +``` + + + + +```typescript showLineNumbers title="openai_non_streaming.ts" +import OpenAI from 'openai'; + +const client = new OpenAI({ + apiKey: 'sk-1234', // Your LiteLLM Virtual Key + baseURL: 'http://localhost:4000' // Your LiteLLM proxy URL +}); + +const response = await client.chat.completions.create({ + model: 'a2a/my-agent', // Use a2a/ prefix with your agent name + messages: [ + { role: 'user', content: 'Hello, what can you do?' } + ] +}); + +console.log(response.choices[0].message.content); +``` + + + + +```bash showLineNumbers title="curl_non_streaming.sh" +curl -X POST http://localhost:4000/v1/chat/completions \ + -H "Authorization: Bearer sk-1234" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "a2a/my-agent", + "messages": [ + {"role": "user", "content": "Hello, what can you do?"} + ] + }' +``` + + + + +### Streaming + + + + +```python showLineNumbers title="openai_streaming.py" +import openai + +client = openai.OpenAI( + api_key="sk-1234", # Your LiteLLM Virtual Key + base_url="http://localhost:4000" # Your LiteLLM proxy URL +) + +stream = client.chat.completions.create( + model="a2a/my-agent", # Use a2a/ prefix with your agent name + messages=[ + {"role": "user", "content": "Tell me a long story"} + ], + stream=True +) + +for chunk in stream: + if chunk.choices[0].delta.content: + print(chunk.choices[0].delta.content, end="", flush=True) +``` + + + + +```typescript showLineNumbers title="openai_streaming.ts" +import OpenAI from 'openai'; + +const client = new OpenAI({ + apiKey: 'sk-1234', // Your LiteLLM Virtual Key + baseURL: 'http://localhost:4000' // Your LiteLLM proxy URL +}); + +const stream = await client.chat.completions.create({ + model: 'a2a/my-agent', // Use a2a/ prefix with your agent name + messages: [ + { role: 'user', content: 'Tell me a long story' } + ], + stream: true +}); + +for await (const chunk of stream) { + const content = chunk.choices[0]?.delta?.content; + if (content) { + process.stdout.write(content); + } +} +``` + + + + +```bash showLineNumbers title="curl_streaming.sh" +curl -X POST http://localhost:4000/v1/chat/completions \ + -H "Authorization: Bearer sk-1234" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "a2a/my-agent", + "messages": [ + {"role": "user", "content": "Tell me a long story"} + ], + "stream": true + }' +``` + + + + +## Key Differences + +| Method | Use Case | Advantages | +|--------|----------|------------| +| **A2A SDK** | Native A2A protocol integration | • Full A2A protocol support
• Access to task states and artifacts
• Context management | +| **OpenAI SDK** | Familiar OpenAI-style interface | • Drop-in replacement for OpenAI calls
• Easier migration from LLM to agent workflows
• Works with existing OpenAI tooling | + +:::tip Model Prefix + +When using the OpenAI SDK, always prefix your agent name with `a2a/` (e.g., `a2a/my-agent`) to route requests to the A2A agent instead of an LLM provider. + +::: diff --git a/docs/my-website/docs/adding_provider/simple_guardrail_tutorial.md b/docs/my-website/docs/adding_provider/simple_guardrail_tutorial.md index 9c654cd1560..884a7397bde 100644 --- a/docs/my-website/docs/adding_provider/simple_guardrail_tutorial.md +++ b/docs/my-website/docs/adding_provider/simple_guardrail_tutorial.md @@ -101,12 +101,11 @@ model_list: - model_name: gpt-4 litellm_params: model: gpt-4 - api_key: os.environ/OPENAI_API_KEY + api_key: os.environ/OPENAI_API_KEY -litellm_settings: - guardrails: +guardrails: - guardrail_name: my_guardrail - litellm_params: + litellm_params: guardrail: my_guardrail mode: during_call api_key: os.environ/MY_GUARDRAIL_API_KEY diff --git a/docs/my-website/docs/completion/web_search.md b/docs/my-website/docs/completion/web_search.md index db50c7b5bc5..9ba66c730f0 100644 --- a/docs/my-website/docs/completion/web_search.md +++ b/docs/my-website/docs/completion/web_search.md @@ -18,12 +18,29 @@ Each provider uses their own search backend: | Provider | Search Engine | Notes | |----------|---------------|-------| -| **OpenAI** (`gpt-4o-search-preview`) | OpenAI's internal search | Real-time web data | +| **OpenAI** (`gpt-4o-search-preview`, `gpt-4o-mini-search-preview`, `gpt-5-search-api`) | OpenAI's internal search | Real-time web data | | **xAI** (`grok-3`) | xAI's search + X/Twitter | Real-time social media data | | **Google AI/Vertex** (`gemini-2.0-flash`) | **Google Search** | Uses actual Google search results | | **Anthropic** (`claude-3-5-sonnet`) | Anthropic's web search | Real-time web data | | **Perplexity** | Perplexity's search engine | AI-powered search and reasoning | +:::warning Important: Only Search Models Support `web_search_options` +For OpenAI, only dedicated search models support the `web_search_options` parameter: +- `gpt-4o-search-preview` +- `gpt-4o-mini-search-preview` +- `gpt-5-search-api` + +**Regular models like `gpt-5`, `gpt-4.1`, `gpt-4o` do not support `web_search_options`** +::: + +:::tip The `web_search_options` parameter is optional +Search models (like `gpt-4o-search-preview`) **automatically search the web** even without the `web_search_options` parameter. + +Use `web_search_options` when you need to: +- Adjust `search_context_size` (`"low"`, `"medium"`, `"high"`) +- Specify `user_location` for localized results +::: + :::info **Anthropic Web Search Models**: Claude models that support web search: `claude-3-5-sonnet-latest`, `claude-3-5-sonnet-20241022`, `claude-3-5-haiku-latest`, `claude-3-5-haiku-20241022`, `claude-3-7-sonnet-20250219` ::: diff --git a/docs/my-website/docs/enterprise.md b/docs/my-website/docs/enterprise.md index 2eed0f53e59..0a1b47f0621 100644 --- a/docs/my-website/docs/enterprise.md +++ b/docs/my-website/docs/enterprise.md @@ -74,6 +74,18 @@ You can find [supported data regions litellm here](../docs/data_security#support ## Frequently Asked Questions +### How to set up and verify your Enterprise License + +1. Add your license key to the environment: + +```env +LITELLM_LICENSE="eyJ..." +``` + +2. Restart LiteLLM Proxy. + +3. Open `http://:/` — the Swagger page should show **"Enterprise Edition"** in the description. If it doesn't, check that the key is correct, unexpired, and that the proxy was fully restarted. + ### SLA's + Professional Support Professional Support can assist with LLM/Provider integrations, deployment, upgrade management, and LLM Provider troubleshooting. We can’t solve your own infrastructure-related issues but we will guide you to fix them. diff --git a/docs/my-website/docs/mcp_public_internet.md b/docs/my-website/docs/mcp_public_internet.md new file mode 100644 index 00000000000..69dd7464657 --- /dev/null +++ b/docs/my-website/docs/mcp_public_internet.md @@ -0,0 +1,251 @@ +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# Exposing MCPs on the Public Internet + +Control which MCP servers are visible to external callers (e.g., ChatGPT, Claude Desktop) vs. internal-only callers. This is useful when you want a subset of your MCP servers available publicly while keeping sensitive servers restricted to your private network. + +## Overview + +| Property | Details | +|-------|-------| +| Description | IP-based access control for MCP servers — external callers only see servers marked as public | +| Setting | `available_on_public_internet` on each MCP server | +| Network Config | `mcp_internal_ip_ranges` in `general_settings` | +| Supported Clients | ChatGPT, Claude Desktop, Cursor, OpenAI API, or any MCP client | + +## How It Works + +When a request arrives at LiteLLM's MCP endpoints, LiteLLM checks the caller's IP address to determine whether they are an **internal** or **external** caller: + +1. **Extract the client IP** from the incoming request (supports `X-Forwarded-For` when configured behind a reverse proxy). +2. **Classify the IP** as internal or external by checking it against the configured private IP ranges (defaults to RFC 1918: `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `127.0.0.0/8`). +3. **Filter the server list**: + - **Internal callers** see all MCP servers (public and private). + - **External callers** only see servers with `available_on_public_internet: true`. + +This filtering is applied at every MCP access point: the MCP registry, tool listing, tool calling, dynamic server routes, and OAuth discovery endpoints. + +```mermaid +flowchart TD + A[Incoming MCP Request] --> B[Extract Client IP Address] + B --> C{Is IP in private ranges?} + C -->|Yes - Internal caller| D[Return ALL MCP servers] + C -->|No - External caller| E[Return ONLY servers with
available_on_public_internet = true] +``` + +## Walkthrough + +This walkthrough covers two flows: +1. **Adding a public MCP server** (DeepWiki) and connecting to it from ChatGPT +2. **Making an existing server private** (Exa) and verifying ChatGPT no longer sees it + +### Flow 1: Add a Public MCP Server (DeepWiki) + +DeepWiki is a free MCP server — a good candidate to expose publicly so AI gateway users can access it from ChatGPT. + +#### Step 1: Create the MCP Server + +Navigate to the MCP Servers page and click **"+ Add New MCP Server"**. + +![Click Add New MCP Server](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/28cc27c2-d980-4255-b552-ebf542ef95be/ascreenshot_30a7e3c043834f1c87b69e6ffc5bba4f_text_export.jpeg) + +The create dialog opens. Enter **"DeepWiki"** as the server name. + +![Enter server name](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/8c733c38-310a-40ef-8a5b-7af91cc7f74f/ascreenshot_16df83fed5bd4683a22a042e07063cec_text_export.jpeg) + +For the transport type dropdown, select **HTTP** since DeepWiki uses the Streamable HTTP transport. + +![Select transport type](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/e473f603-d692-40c7-a218-866c2e1cb554/ascreenshot_e93997971f2f44beac6152786889addf_text_export.jpeg) + +Now scroll down to the MCP Server URL field. + +![Configure server](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/b08d3c1f-9279-45b6-8efb-f73008901da6/ascreenshot_ce0de66f230a41b0a454e76653429021_text_export.jpeg) + +Enter the DeepWiki MCP URL: `https://mcp.deepwiki.com/mcp`. + +![Enter MCP server URL](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/e59f8285-cfde-4c57-aa79-24244acc9160/ascreenshot_8d575c66dc614a4183212ba282d22b41_text_export.jpeg) + +With the name, transport, and URL filled in, the basic server configuration is complete. + +![Server URL configured](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/0f1af7ed-760d-4445-bdec-3da706d4eef4/ascreenshot_d7d6db69bc254ded871d14a71188a212_text_export.jpeg) + +#### Step 2: Enable "Available on Public Internet" + +Before creating, scroll down and expand the **Permission Management / Access Control** section. This is where you control who can see this server. + +![Expand Permission Management](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/cc10dea2-6028-4a27-a33b-1b1b7212efb5/ascreenshot_0fdd152b862a4bf39973bc805ce64c57_text_export.jpeg) + +Toggle **"Available on Public Internet"** on. This is the key setting — it tells LiteLLM that external callers (like ChatGPT connecting from the public internet) should be able to discover and use this server. + +![Toggle Available on Public Internet](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/39c14543-c5ae-4189-8f85-9efc87135820/ascreenshot_9991f54910c24e21bba5c05ea4fa8e28_text_export.jpeg) + +With the toggle enabled, click **"Create"** to save the server. + +![Click Create](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/843be209-aade-44f4-98da-e55d1644854c/ascreenshot_8cfc90345a5f4d069b397e80d0a6e449_text_export.jpeg) + +#### Step 3: Connect from ChatGPT + +Now let's verify it works. Open ChatGPT and look for the MCP server icon to add a new connection. The endpoint to use is `/mcp`. + +![ChatGPT add MCP server](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/58b5f674-edf4-4156-a5fa-5fdc8ed5d7b9/ascreenshot_36735f7c37394e919793968794614126_text_export.jpeg) + +In the dropdown, select **"Add an MCP server"** to configure a new connection. + +![ChatGPT MCP server option](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/f89da8af-bc61-44a7-a765-f52733f4970d/ascreenshot_6410a917b782437eb558de3bfcd35ffd_text_export.jpeg) + +ChatGPT asks for a server label. Give it a recognizable name like "LiteLLM". + +![Enter server label](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/88505afe-07c1-4674-a89c-8035a5d05eb6/ascreenshot_143aefc38ddd4d3f9f5823ca2cc09bc2_text_export.jpeg) + +Next, enter the Server URL. This should be your LiteLLM proxy's MCP endpoint — `/mcp`. + +![Enter LiteLLM MCP URL](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/9048be4a-7e40-43e7-9789-059fed2741a6/ascreenshot_e81232c17fd148f48f0ae552e9dc2a10_text_export.jpeg) + +Paste your LiteLLM URL and confirm it looks correct. + +![URL pasted](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/7707e796-e146-47c8-bce0-58e6f4076272/ascreenshot_0710dc58b8ed4d6887856b1388d59329_text_export.jpeg) + +ChatGPT also needs authentication. Enter your LiteLLM API key in the authentication field so it can connect to the proxy. + +![Enter API key](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/f6cfcb81-021d-4a41-94d7-d4eaf449d025/ascreenshot_d635865abfb64732a7278922f08dbcaa_text_export.jpeg) + +Click **"Connect"** to establish the connection. + +![Click Connect](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/1146b326-6f0c-4050-9729-af5c88e1bc81/ascreenshot_e19fb857e5394b9a9bf77b075b4fb620_text_export.jpeg) + +ChatGPT connects and shows the available tools. Since both DeepWiki and Exa are currently marked as public, ChatGPT can see tools from both servers. + +![ChatGPT shows available MCP tools](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/43ac56b7-9933-4762-903a-370fc52c79b5/ascreenshot_39073d6dc3bc4bb6a79d93365a26a4f8_text_export.jpeg) + +--- + +### Flow 2: Make an Existing Server Private (Exa) + +Now let's do the reverse — take an existing MCP server (Exa) that's currently public and restrict it to internal access only. After this change, ChatGPT should no longer see Exa's tools. + +#### Step 1: Edit the Server + +Go to the MCP Servers table and click on the Exa server to open its detail view. + +![Exa server overview](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/65844f13-b1ec-4092-b3fd-b1cae3c0c833/ascreenshot_cc8ea435c5e14761a1394ca80fe817c0_text_export.jpeg) + +Switch to the **"Settings"** tab to access the edit form. + +![Click Settings](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/d5b65271-561e-4d2a-b832-96d32611f6e4/ascreenshot_a200942b17264c1eb7a3ffdb2c2141f5_text_export.jpeg) + +The edit form loads with Exa's current configuration. + +![Edit server](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/119184f6-f3cd-45b7-9cfa-0ea08de27020/ascreenshot_c39a793da03a4f0fb84b5ee829af9034_text_export.jpeg) + +#### Step 2: Toggle Off "Available on Public Internet" + +Scroll down and expand the **Permission Management / Access Control** section to find the public internet toggle. + +![Expand permissions](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/bf7114cc-8741-4fa0-a39a-fe625482e88a/ascreenshot_8a987649c03e46558a2ec9a6f2f539a4_text_export.jpeg) + +Toggle **"Available on Public Internet"** off. This will hide Exa from any caller outside your private network. + +![Toggle off public internet](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/f36af5ad-028f-4bb1-aed1-43e38ff9b733/ascreenshot_9128364a049f489bb8483e18e5c88015_text_export.jpeg) + +Click **"Save Changes"** to apply. The change takes effect immediately — no proxy restart needed. + +![Save changes](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/126a71b3-02e1-4d61-a208-942b92e9ef25/ascreenshot_f349ef69e08044dd8e4903f4286b7b97_text_export.jpeg) + +#### Step 3: Verify in ChatGPT + +Go back to ChatGPT to confirm Exa is no longer visible. You'll need to reconnect for ChatGPT to re-fetch the tool list. + +![ChatGPT verify](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/15518882-8b19-44d3-9bba-245aeb62b4b1/ascreenshot_f98f59c51e6543e1be4f3960ba375fc9_text_export.jpeg) + +Open the MCP server settings and select to add or reconnect a server. + +![Reconnect to server](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/784d3174-77c0-42e6-a059-4c906db8f72a/ascreenshot_d77db951b83e4b15a00373222712f6b5_text_export.jpeg) + +Enter the same LiteLLM MCP URL as before. + +![Reconnect URL](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/17ef5fb0-b240-4556-8d20-753d359b7fcf/ascreenshot_583466ce9e8f40d1ba0af8b1e7d04413_text_export.jpeg) + +Set the server label. + +![Reconnect name](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/d7907637-c957-4a3c-ab4f-1600ca9a70a0/ascreenshot_e429eea43f3f4b3ca4d3ac5a77fbde2d_text_export.jpeg) + +Enter your API key for authentication. + +![Reconnect key](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/9cfff77a-37aa-4ca6-8032-0b46c50f37e3/ascreenshot_250664183399496b8f5c9f86f576fc0b_text_export.jpeg) + +Click **"Connect"** to re-establish the connection. + +![Click Connect](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/686f6307-b4ae-448b-ac6c-2c9d7b4f6b57/ascreenshot_3f499d0812af42ab89fed103cc21c249_text_export.jpeg) + +This time, only DeepWiki's tools appear — Exa is gone. LiteLLM detected that ChatGPT is calling from a public IP and filtered out Exa since it's no longer marked as public. Internal users on your private network would still see both servers. + +![Only DeepWiki tools visible](https://colony-recorder.s3.amazonaws.com/files/2026-02-07/667d79b6-75f9-4799-9315-0c176e7a5e34/ascreenshot_efa43050ac0b4445a09e542fa8f270ff_text_export.jpeg) + +## Configuration Reference + +### Per-Server Setting + + + + +Toggle **"Available on Public Internet"** in the Permission Management section when creating or editing an MCP server. + + + + +```yaml title="config.yaml" showLineNumbers +mcp_servers: + deepwiki: + url: https://mcp.deepwiki.com/mcp + available_on_public_internet: true # visible to external callers + + exa: + url: https://exa.ai/mcp + auth_type: api_key + auth_value: os.environ/EXA_API_KEY + available_on_public_internet: false # internal only (default) +``` + + + + +```bash title="Create a public MCP server" showLineNumbers +curl -X POST /v1/mcp/server \ + -H "Authorization: Bearer sk-..." \ + -H "Content-Type: application/json" \ + -d '{ + "server_name": "DeepWiki", + "url": "https://mcp.deepwiki.com/mcp", + "transport": "http", + "available_on_public_internet": true + }' +``` + +```bash title="Update an existing server" showLineNumbers +curl -X PUT /v1/mcp/server \ + -H "Authorization: Bearer sk-..." \ + -H "Content-Type: application/json" \ + -d '{ + "server_id": "", + "available_on_public_internet": false + }' +``` + + + + +### Custom Private IP Ranges + +By default, LiteLLM treats RFC 1918 private ranges as internal. You can customize this in the **Network Settings** tab under MCP Servers, or via config: + +```yaml title="config.yaml" showLineNumbers +general_settings: + mcp_internal_ip_ranges: + - "10.0.0.0/8" + - "172.16.0.0/12" + - "192.168.0.0/16" + - "100.64.0.0/10" # Add your VPN/Tailscale range +``` + +When empty, the standard private ranges are used (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `127.0.0.0/8`). diff --git a/docs/my-website/docs/mcp_semantic_filter.md b/docs/my-website/docs/mcp_semantic_filter.md new file mode 100644 index 00000000000..c58be80a680 --- /dev/null +++ b/docs/my-website/docs/mcp_semantic_filter.md @@ -0,0 +1,158 @@ +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# MCP Semantic Tool Filter + +Automatically filter MCP tools by semantic relevance. When you have many MCP tools registered, LiteLLM semantically matches the user's query against tool descriptions and sends only the most relevant tools to the LLM. + +## How It Works + +Tool search shifts tool selection from a prompt-engineering problem to a retrieval problem. Instead of injecting a large static list of tools into every prompt, the semantic filter: + +1. Builds a semantic index of all available MCP tools on startup +2. On each request, semantically matches the user's query against tool descriptions +3. Returns only the top-K most relevant tools to the LLM + +This approach improves context efficiency, increases reliability by reducing tool confusion, and enables scalability to ecosystems with hundreds or thousands of MCP tools. + +```mermaid +sequenceDiagram + participant Client + participant LiteLLM as LiteLLM Proxy + participant SemanticFilter as Semantic Filter + participant MCP as MCP Registry + participant LLM as LLM Provider + + Note over LiteLLM,MCP: Startup: Build Semantic Index + LiteLLM->>MCP: Fetch all registered MCP tools + MCP->>LiteLLM: Return all tools (e.g., 50 tools) + LiteLLM->>SemanticFilter: Build semantic router with embeddings + SemanticFilter->>LLM: Generate embeddings for tool descriptions + LLM->>SemanticFilter: Return embeddings + Note over SemanticFilter: Index ready for fast lookup + + Note over Client,LLM: Request: Semantic Tool Filtering + Client->>LiteLLM: POST /v1/responses with MCP tools + LiteLLM->>SemanticFilter: Expand MCP references (50 tools available) + SemanticFilter->>SemanticFilter: Extract user query from request + SemanticFilter->>LLM: Generate query embedding + LLM->>SemanticFilter: Return query embedding + SemanticFilter->>SemanticFilter: Match query against tool embeddings + SemanticFilter->>LiteLLM: Return top-K tools (e.g., 3 most relevant) + LiteLLM->>LLM: Forward request with filtered tools (3 tools) + LLM->>LiteLLM: Return response + LiteLLM->>Client: Response with headers
x-litellm-semantic-filter: 50->3
x-litellm-semantic-filter-tools: tool1,tool2,tool3 +``` + +## Configuration + +Enable semantic filtering in your LiteLLM config: + +```yaml title="config.yaml" showLineNumbers +litellm_settings: + mcp_semantic_tool_filter: + enabled: true + embedding_model: "text-embedding-3-small" # Model for semantic matching + top_k: 5 # Max tools to return + similarity_threshold: 0.3 # Min similarity score +``` + +**Configuration Options:** +- `enabled` - Enable/disable semantic filtering (default: `false`) +- `embedding_model` - Model for generating embeddings (default: `"text-embedding-3-small"`) +- `top_k` - Maximum number of tools to return (default: `10`) +- `similarity_threshold` - Minimum similarity score for matches (default: `0.3`) + +## Usage + +Use MCP tools normally with the Responses API or Chat Completions. The semantic filter runs automatically: + + + + +```bash title="Responses API with Semantic Filtering" showLineNumbers +curl --location 'http://localhost:4000/v1/responses' \ +--header 'Content-Type: application/json' \ +--header "Authorization: Bearer sk-1234" \ +--data '{ + "model": "gpt-4o", + "input": [ + { + "role": "user", + "content": "give me TLDR of what BerriAI/litellm repo is about", + "type": "message" + } + ], + "tools": [ + { + "type": "mcp", + "server_url": "litellm_proxy", + "require_approval": "never" + } + ], + "tool_choice": "required" +}' +``` + + + + +```bash title="Chat Completions with Semantic Filtering" showLineNumbers +curl --location 'http://localhost:4000/v1/chat/completions' \ +--header 'Content-Type: application/json' \ +--header "Authorization: Bearer sk-1234" \ +--data '{ + "model": "gpt-4o", + "messages": [ + {"role": "user", "content": "Search Wikipedia for LiteLLM"} + ], + "tools": [ + { + "type": "mcp", + "server_url": "litellm_proxy" + } + ] +}' +``` + + + + +## Response Headers + +The semantic filter adds diagnostic headers to every response: + +``` +x-litellm-semantic-filter: 10->3 +x-litellm-semantic-filter-tools: wikipedia-fetch,github-search,slack-post +``` + +- **`x-litellm-semantic-filter`** - Shows before→after tool count (e.g., `10->3` means 10 tools were filtered down to 3) +- **`x-litellm-semantic-filter-tools`** - CSV list of the filtered tool names (max 150 chars, clipped with `...` if longer) + +These headers help you understand which tools were selected for each request and verify the filter is working correctly. + +## Example + +If you have 50 MCP tools registered and make a request asking about Wikipedia, the semantic filter will: + +1. Semantically match your query `"Search Wikipedia for LiteLLM"` against all 50 tool descriptions +2. Select the top 5 most relevant tools (e.g., `wikipedia-fetch`, `wikipedia-search`, etc.) +3. Pass only those 5 tools to the LLM +4. Add headers showing `x-litellm-semantic-filter: 50->5` + +This dramatically reduces prompt size while ensuring the LLM has access to the right tools for the task. + +## Performance + +The semantic filter is optimized for production: +- Router builds once on startup (no per-request overhead) +- Semantic matching typically takes under 50ms +- Fails gracefully - returns all tools if filtering fails +- No impact on latency for requests without MCP tools + +## Related + +- [MCP Overview](./mcp.md) - Learn about MCP in LiteLLM +- [MCP Permission Management](./mcp_control.md) - Control tool access by key/team +- [Using MCP](./mcp_usage.md) - Complete MCP usage guide diff --git a/docs/my-website/docs/observability/langfuse_integration.md b/docs/my-website/docs/observability/langfuse_integration.md index a81336c5bc6..d3c5a44d481 100644 --- a/docs/my-website/docs/observability/langfuse_integration.md +++ b/docs/my-website/docs/observability/langfuse_integration.md @@ -215,6 +215,66 @@ The following parameters can be updated on a continuation of a trace by passing Any other key value pairs passed into the metadata not listed in the above spec for a `litellm` completion will be added as a metadata key value pair for the generation. +#### Multiple Langfuse Projects (Per-Request Credentials) + +You can send traces to different Langfuse projects per request by passing credentials directly to `completion()` or `acompletion()`. This works alongside (or instead of) the global env vars and is useful when different teams or business processes use different Langfuse projects. + +Pass **`langfuse_public_key`**, **`langfuse_secret_key`** (or **`langfuse_secret`**), and optionally **`langfuse_host`** as keyword arguments: + +```python +import litellm +from litellm import completion + +# Optional: set a default via env for requests that don't pass credentials +# os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-default..." +# os.environ["LANGFUSE_SECRET_KEY"] = "sk-default..." + +litellm.success_callback = ["langfuse"] +litellm.failure_callback = ["langfuse"] + +# Request 1 → Langfuse Project A +response_a = completion( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hello from team A"}], + langfuse_public_key="pk-lf-project-a...", + langfuse_secret_key="sk-lf-project-a...", + langfuse_host="https://us.cloud.langfuse.com", # optional +) + +# Request 2 → Langfuse Project B (different project) +response_b = completion( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hello from team B"}], + langfuse_public_key="pk-lf-project-b...", + langfuse_secret_key="sk-lf-project-b...", + langfuse_host="https://eu.cloud.langfuse.com", # optional, can differ per project +) +``` + +Async usage with per-request credentials: + +```python +import litellm +from litellm import acompletion + +litellm.success_callback = ["langfuse"] +litellm.failure_callback = ["langfuse"] + +response = await acompletion( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hi"}], + langfuse_public_key="pk-lf-...", + langfuse_secret_key="sk-lf-...", + langfuse_host="https://us.cloud.langfuse.com", # optional +) +``` + +- **`langfuse_public_key`** – Langfuse project public key (required for per-request override). +- **`langfuse_secret_key`** or **`langfuse_secret`** – Langfuse secret key (either name is accepted). +- **`langfuse_host`** – Langfuse host URL (e.g. `https://us.cloud.langfuse.com`); optional, defaults to env or Langfuse cloud. + +When these are passed, that request uses this project (and host) for the Langfuse callback; when omitted, the callback uses the global Langfuse client (from env vars if set). LiteLLM caches a Langfuse client per credential set to avoid creating a new client on every request. + #### Disable Logging - Specific Calls To disable logging for specific calls use the `no-log` flag. diff --git a/docs/my-website/docs/providers/bedrock.md b/docs/my-website/docs/providers/bedrock.md index 487212ad655..e546ed97656 100644 --- a/docs/my-website/docs/providers/bedrock.md +++ b/docs/my-website/docs/providers/bedrock.md @@ -9,7 +9,7 @@ ALL Bedrock models (Anthropic, Meta, Deepseek, Mistral, Amazon, etc.) are Suppor | Description | Amazon Bedrock is a fully managed service that offers a choice of high-performing foundation models (FMs). | | Provider Route on LiteLLM | `bedrock/`, [`bedrock/converse/`](#set-converse--invoke-route), [`bedrock/invoke/`](#set-invoke-route), [`bedrock/converse_like/`](#calling-via-internal-proxy), [`bedrock/llama/`](#deepseek-not-r1), [`bedrock/deepseek_r1/`](#deepseek-r1), [`bedrock/qwen3/`](#qwen3-imported-models), [`bedrock/qwen2/`](./bedrock_imported.md#qwen2-imported-models), [`bedrock/openai/`](./bedrock_imported.md#openai-compatible-imported-models-qwen-25-vl-etc), [`bedrock/moonshot`](./bedrock_imported.md#moonshot-kimi-k2-thinking) | | Provider Doc | [Amazon Bedrock ↗](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) | -| Supported OpenAI Endpoints | `/chat/completions`, `/completions`, `/embeddings`, `/images/generations` | +| Supported OpenAI Endpoints | `/chat/completions`, `/completions`, `/embeddings`, `/images/generations`, `/v1/realtime`| | Rerank Endpoint | `/rerank` | | Pass-through Endpoint | [Supported](../pass_through/bedrock.md) | diff --git a/docs/my-website/docs/providers/bedrock_realtime_with_audio.md b/docs/my-website/docs/providers/bedrock_realtime_with_audio.md new file mode 100644 index 00000000000..a2d9813ffd9 --- /dev/null +++ b/docs/my-website/docs/providers/bedrock_realtime_with_audio.md @@ -0,0 +1,362 @@ +# Bedrock Realtime API + +## Overview + +Amazon Bedrock's Nova Sonic model supports real-time bidirectional audio streaming for voice conversations. This tutorial shows how to use it through LiteLLM Proxy. + +## Setup + +### 1. Configure LiteLLM Proxy + +Create a `config.yaml` file: + +```yaml +model_list: + - model_name: "bedrock-sonic" + litellm_params: + model: bedrock/amazon.nova-sonic-v1:0 + aws_region_name: us-east-1 # or your preferred region + model_info: + mode: realtime +``` + +### 2. Start LiteLLM Proxy + +```bash +litellm --config config.yaml +``` + +## Basic Text Interaction + +```python +import asyncio +import websockets +import json + +LITELLM_API_KEY = "sk-1234" # Your LiteLLM API key +LITELLM_URL = 'ws://localhost:4000/v1/realtime?model=bedrock-sonic' + +async def test_text_conversation(): + async with websockets.connect( + LITELLM_URL, + additional_headers={ + "Authorization": f"Bearer {LITELLM_API_KEY}" + } + ) as ws: + # Wait for session.created + response = await ws.recv() + print(f"Connected: {json.loads(response)['type']}") + + # Configure session + session_update = { + "type": "session.update", + "session": { + "instructions": "You are a helpful assistant.", + "modalities": ["text"], + "temperature": 0.8 + } + } + await ws.send(json.dumps(session_update)) + + # Send a message + message = { + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "Hello!"}] + } + } + await ws.send(json.dumps(message)) + + # Trigger response + await ws.send(json.dumps({"type": "response.create"})) + + # Listen for response + while True: + response = await ws.recv() + event = json.loads(response) + + if event['type'] == 'response.text.delta': + print(event['delta'], end='', flush=True) + elif event['type'] == 'response.done': + print("\n✓ Complete") + break + +if __name__ == "__main__": + asyncio.run(test_text_conversation()) +``` + +## Audio Streaming with Voice Conversation + +```python +import asyncio +import websockets +import json +import base64 +import pyaudio + +LITELLM_API_KEY = "sk-1234" +LITELLM_URL = 'ws://localhost:4000/v1/realtime?model=bedrock-sonic' + +# Audio configuration +INPUT_RATE = 16000 # Nova Sonic expects 16kHz input +OUTPUT_RATE = 24000 # Nova Sonic outputs 24kHz +CHUNK = 1024 + +async def audio_conversation(): + # Initialize PyAudio + p = pyaudio.PyAudio() + + # Input stream (microphone) + input_stream = p.open( + format=pyaudio.paInt16, + channels=1, + rate=INPUT_RATE, + input=True, + frames_per_buffer=CHUNK + ) + + # Output stream (speakers) + output_stream = p.open( + format=pyaudio.paInt16, + channels=1, + rate=OUTPUT_RATE, + output=True, + frames_per_buffer=CHUNK + ) + + async with websockets.connect( + LITELLM_URL, + additional_headers={"Authorization": f"Bearer {LITELLM_API_KEY}"} + ) as ws: + # Wait for session.created + await ws.recv() + print("✓ Connected") + + # Configure session with audio + session_update = { + "type": "session.update", + "session": { + "instructions": "You are a friendly voice assistant.", + "modalities": ["text", "audio"], + "voice": "matthew", + "input_audio_format": "pcm16", + "output_audio_format": "pcm16" + } + } + await ws.send(json.dumps(session_update)) + print("🎤 Speak into your microphone...") + + async def send_audio(): + """Capture and send audio from microphone""" + while True: + audio_data = input_stream.read(CHUNK, exception_on_overflow=False) + audio_b64 = base64.b64encode(audio_data).decode('utf-8') + await ws.send(json.dumps({ + "type": "input_audio_buffer.append", + "audio": audio_b64 + })) + await asyncio.sleep(0.01) + + async def receive_audio(): + """Receive and play audio responses""" + while True: + response = await ws.recv() + event = json.loads(response) + + if event['type'] == 'response.audio.delta': + audio_b64 = event.get('delta', '') + if audio_b64: + audio_bytes = base64.b64decode(audio_b64) + output_stream.write(audio_bytes) + + elif event['type'] == 'response.text.delta': + print(event['delta'], end='', flush=True) + + elif event['type'] == 'response.done': + print("\n✓ Response complete") + + # Run both tasks concurrently + await asyncio.gather(send_audio(), receive_audio()) + +if __name__ == "__main__": + try: + asyncio.run(audio_conversation()) + except KeyboardInterrupt: + print("\n\nGoodbye!") +``` + +## Using Tools/Function Calling + +```python +import asyncio +import websockets +import json +from datetime import datetime + +LITELLM_API_KEY = "sk-1234" +LITELLM_URL = 'ws://localhost:4000/v1/realtime?model=bedrock-sonic' + +# Define tools +TOOLS = [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get current weather for a location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "City name" + } + }, + "required": ["location"] + } + } + } +] + +def get_weather(location: str) -> dict: + """Simulated weather function""" + return { + "location": location, + "temperature": 72, + "conditions": "sunny" + } + +async def conversation_with_tools(): + async with websockets.connect( + LITELLM_URL, + additional_headers={"Authorization": f"Bearer {LITELLM_API_KEY}"} + ) as ws: + # Wait for session.created + await ws.recv() + + # Configure session with tools + session_update = { + "type": "session.update", + "session": { + "instructions": "You are a helpful assistant with access to tools.", + "modalities": ["text"], + "tools": TOOLS + } + } + await ws.send(json.dumps(session_update)) + + # Send a message that requires a tool + message = { + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "What's the weather in San Francisco?"}] + } + } + await ws.send(json.dumps(message)) + await ws.send(json.dumps({"type": "response.create"})) + + # Handle responses and tool calls + while True: + response = await ws.recv() + event = json.loads(response) + + if event['type'] == 'response.text.delta': + print(event['delta'], end='', flush=True) + + elif event['type'] == 'response.function_call_arguments.done': + # Execute the tool + function_name = event['name'] + arguments = json.loads(event['arguments']) + + print(f"\n🔧 Calling {function_name}({arguments})") + result = get_weather(**arguments) + + # Send tool result back + tool_result = { + "type": "conversation.item.create", + "item": { + "type": "function_call_output", + "call_id": event['call_id'], + "output": json.dumps(result) + } + } + await ws.send(json.dumps(tool_result)) + await ws.send(json.dumps({"type": "response.create"})) + + elif event['type'] == 'response.done': + print("\n✓ Complete") + break + +if __name__ == "__main__": + asyncio.run(conversation_with_tools()) +``` + +## Configuration Options + +### Voice Options +Available voices: `matthew`, `joanna`, `ruth`, `stephen`, `gregory`, `amy` + +### Audio Formats +- **Input**: 16kHz PCM16 (mono) +- **Output**: 24kHz PCM16 (mono) + +### Modalities +- `["text"]` - Text only +- `["audio"]` - Audio only +- `["text", "audio"]` - Both text and audio + +## Example Test Scripts + +Complete working examples are available in the LiteLLM repository: + +- **Basic audio streaming**: `test_bedrock_realtime_client.py` +- **Simple text test**: `test_bedrock_realtime_simple.py` +- **Tool calling**: `test_bedrock_realtime_tools.py` + +## Requirements + +```bash +pip install litellm websockets pyaudio +``` + +## AWS Configuration + +Ensure your AWS credentials are configured: + +```bash +export AWS_ACCESS_KEY_ID=your_access_key +export AWS_SECRET_ACCESS_KEY=your_secret_key +export AWS_REGION_NAME=us-east-1 +``` + +Or use AWS CLI configuration: + +```bash +aws configure +``` + +## Troubleshooting + +### Connection Issues +- Ensure LiteLLM proxy is running on the correct port +- Verify AWS credentials are properly configured +- Check that the Bedrock model is available in your region + +### Audio Issues +- Verify PyAudio is properly installed +- Check microphone/speaker permissions +- Ensure correct sample rates (16kHz input, 24kHz output) + +### Tool Calling Issues +- Ensure tools are properly defined in session.update +- Verify tool results are sent back with correct call_id +- Check that response.create is sent after tool result + +## Related Resources + +- [OpenAI Realtime API Documentation](https://platform.openai.com/docs/guides/realtime) +- [Amazon Bedrock Nova Sonic Documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/nova-sonic.html) +- [LiteLLM Realtime API Documentation](/docs/realtime) diff --git a/docs/my-website/docs/providers/elevenlabs.md b/docs/my-website/docs/providers/elevenlabs.md index 5cf62f51203..b4ed3d3346b 100644 --- a/docs/my-website/docs/providers/elevenlabs.md +++ b/docs/my-website/docs/providers/elevenlabs.md @@ -243,6 +243,13 @@ ElevenLabs provides high-quality text-to-speech capabilities through their TTS A | Supported Operations | `/audio/speech` | | Link to Provider Doc | [ElevenLabs TTS API ↗](https://elevenlabs.io/docs/api-reference/text-to-speech) | +### Supported Models + +| Model | Route | Description | +|-------|-------|-------------| +| Eleven v3 | `elevenlabs/eleven_v3` | Most expressive model. 70+ languages, audio tags support for sound effects and pauses. | +| Eleven Multilingual v2 | `elevenlabs/eleven_multilingual_v2` | Default TTS model. 29 languages, stable and production-ready. | + ### Quick Start #### LiteLLM Python SDK @@ -265,6 +272,26 @@ with open("test_output.mp3", "wb") as f: f.write(audio.read()) ``` +#### Using Eleven v3 with Audio Tags + +Eleven v3 supports [audio tags](https://elevenlabs.io/docs/overview/capabilities/text-to-speech#audio-tags) for adding sound effects and pauses directly in the text: + +```python showLineNumbers title="Eleven v3 with audio tags" +import litellm +import os + +os.environ["ELEVENLABS_API_KEY"] = "your-elevenlabs-api-key" + +audio = litellm.speech( + model="elevenlabs/eleven_v3", + input='Welcome back. applause Today we have a special guest. Let me introduce them.', + voice="alloy", +) + +with open("eleven_v3_output.mp3", "wb") as f: + f.write(audio.read()) +``` + #### Advanced Usage: Overriding Parameters and ElevenLabs-Specific Features ```python showLineNumbers title="Advanced TTS with custom parameters" diff --git a/docs/my-website/docs/providers/github_copilot.md b/docs/my-website/docs/providers/github_copilot.md index 306c9f949ec..e9fd3444f5f 100644 --- a/docs/my-website/docs/providers/github_copilot.md +++ b/docs/my-website/docs/providers/github_copilot.md @@ -35,11 +35,10 @@ from litellm import completion response = completion( model="github_copilot/gpt-4", - messages=[{"role": "user", "content": "Write a Python function to calculate fibonacci numbers"}], - extra_headers={ - "editor-version": "vscode/1.85.1", - "Copilot-Integration-Id": "vscode-chat" - } + messages=[ + {"role": "system", "content": "You are a helpful coding assistant"}, + {"role": "user", "content": "Write a Python function to calculate fibonacci numbers"} + ] ) print(response) ``` @@ -50,11 +49,7 @@ from litellm import completion stream = completion( model="github_copilot/gpt-4", messages=[{"role": "user", "content": "Explain async/await in Python"}], - stream=True, - extra_headers={ - "editor-version": "vscode/1.85.1", - "Copilot-Integration-Id": "vscode-chat" - } + stream=True ) for chunk in stream: @@ -134,11 +129,7 @@ client = OpenAI( # Non-streaming response response = client.chat.completions.create( model="github_copilot/gpt-4", - messages=[{"role": "user", "content": "How do I optimize this SQL query?"}], - extra_headers={ - "editor-version": "vscode/1.85.1", - "Copilot-Integration-Id": "vscode-chat" - } + messages=[{"role": "user", "content": "How do I optimize this SQL query?"}] ) print(response.choices[0].message.content) @@ -156,11 +147,7 @@ response = litellm.completion( model="litellm_proxy/github_copilot/gpt-4", messages=[{"role": "user", "content": "Review this code for bugs"}], api_base="http://localhost:4000", - api_key="your-proxy-api-key", - extra_headers={ - "editor-version": "vscode/1.85.1", - "Copilot-Integration-Id": "vscode-chat" - } + api_key="your-proxy-api-key" ) print(response.choices[0].message.content) @@ -174,8 +161,6 @@ print(response.choices[0].message.content) curl http://localhost:4000/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your-proxy-api-key" \ - -H "editor-version: vscode/1.85.1" \ - -H "Copilot-Integration-Id: vscode-chat" \ -d '{ "model": "github_copilot/gpt-4", "messages": [{"role": "user", "content": "Explain this error message"}] @@ -211,9 +196,11 @@ export GITHUB_COPILOT_API_KEY_FILE="api-key.json" ### Headers -GitHub Copilot supports various editor-specific headers: +LiteLLM automatically injects the required GitHub Copilot headers (simulating VSCode). You don't need to specify them manually. -```python showLineNumbers title="Common Headers" +If you want to override the defaults (e.g., to simulate a different editor), you can use `extra_headers`: + +```python showLineNumbers title="Custom Headers (Optional)" extra_headers = { "editor-version": "vscode/1.85.1", # Editor version "editor-plugin-version": "copilot/1.155.0", # Plugin version diff --git a/docs/my-website/docs/providers/vertex_speech.md b/docs/my-website/docs/providers/vertex_speech.md index d0acacb5aec..751782a323c 100644 --- a/docs/my-website/docs/providers/vertex_speech.md +++ b/docs/my-website/docs/providers/vertex_speech.md @@ -312,6 +312,7 @@ Gemini models with audio output capabilities using the chat completions API. - Only supports `pcm16` audio format - Streaming not yet supported - Must set `modalities: ["audio"]` +- When using via LiteLLM Proxy, must include `"allowed_openai_params": ["audio", "modalities"]` in the request body to enable audio parameters ::: ### Quick Start @@ -372,7 +373,8 @@ curl http://0.0.0.0:4000/v1/chat/completions \ "model": "gemini-tts", "messages": [{"role": "user", "content": "Say hello in a friendly voice"}], "modalities": ["audio"], - "audio": {"voice": "Kore", "format": "pcm16"} + "audio": {"voice": "Kore", "format": "pcm16"}, + "allowed_openai_params": ["audio", "modalities"] }' ``` @@ -389,6 +391,7 @@ response = client.chat.completions.create( messages=[{"role": "user", "content": "Say hello in a friendly voice"}], modalities=["audio"], audio={"voice": "Kore", "format": "pcm16"}, + extra_body={"allowed_openai_params": ["audio", "modalities"]} ) print(response) ``` diff --git a/docs/my-website/docs/providers/xai_realtime.md b/docs/my-website/docs/providers/xai_realtime.md new file mode 100644 index 00000000000..b36908c4686 --- /dev/null +++ b/docs/my-website/docs/providers/xai_realtime.md @@ -0,0 +1,308 @@ +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# xAI Voice Agent (Realtime API) + +xAI's Grok Voice Agent provides real-time voice conversation capabilities through WebSocket connections, enabling natural bidirectional audio interactions. + +| Feature | Description | Comments | +| --- | --- | --- | +| LiteLLM AI Gateway | ✅ | | +| LiteLLM Python SDK | ✅ | Full support via `litellm.realtime()` | + +## Quick Start + +### Supported Model + +| Model | Context | Features | +|-------|---------|----------| +| `xai/grok-4-1-fast-non-reasoning` | 2M tokens | Voice conversation, Function calling, Vision, Audio, Web search, Caching | + +**Note:** xAI Realtime API uses the non-reasoning variant for optimal real-time performance. + +## Python SDK Usage + +### Basic Realtime Connection + +```python +import asyncio +from litellm import realtime + +async def test_xai_realtime(): + """ + Test xAI Grok Voice Agent via LiteLLM SDK + """ + # Initialize realtime connection + ws = await realtime( + model="xai/grok-4-1-fast-non-reasoning", + api_key="your-xai-api-key", # or set XAI_API_KEY env var + ) + + # Connection established, xAI sends "conversation.created" event + print("Connected to xAI Grok Voice Agent") + + # Send a message + await ws.send_text(json.dumps({ + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [{ + "type": "input_text", + "text": "Hello! How are you?" + }] + } + })) + + # Request a response + await ws.send_text(json.dumps({ + "type": "response.create" + })) + + # Listen for responses + async for message in ws: + data = json.loads(message) + print(f"Received: {data['type']}") + + if data['type'] == 'response.done': + break + + await ws.close() + +# Run the async function +asyncio.run(test_xai_realtime()) +``` + +### With Audio Input/Output + +```python +import asyncio +import json +from litellm import realtime + +async def xai_voice_conversation(): + """ + Voice conversation with xAI Grok Voice Agent + """ + ws = await realtime( + model="xai/grok-4-1-fast-non-reasoning", + api_key="your-xai-api-key", + ) + + # Send audio data (base64 encoded PCM16 24kHz) + await ws.send_text(json.dumps({ + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [{ + "type": "input_audio", + "audio": "base64_encoded_audio_data_here" + }] + } + })) + + # Request response with audio + await ws.send_text(json.dumps({ + "type": "response.create", + "response": { + "modalities": ["text", "audio"], + "instructions": "Please respond in a friendly tone." + } + })) + + # Process streaming audio response + async for message in ws: + data = json.loads(message) + + if data['type'] == 'response.audio.delta': + # Handle audio chunks + audio_chunk = data['delta'] + # Process audio_chunk (play it, save it, etc.) + + elif data['type'] == 'response.done': + break + + await ws.close() + +asyncio.run(xai_voice_conversation()) +``` + +## LiteLLM Proxy (AI Gateway) Usage + +Load balance across multiple xAI deployments or combine with other providers. + +### 1. Add Model to Config + +```yaml +model_list: + - model_name: grok-voice-agent + litellm_params: + model: xai/grok-4-1-fast-non-reasoning + api_key: os.environ/XAI_API_KEY + model_info: + mode: realtime + + # Optional: Add fallback to OpenAI + - model_name: grok-voice-agent + litellm_params: + model: openai/gpt-4o-realtime-preview-2024-10-01 + api_key: os.environ/OPENAI_API_KEY + model_info: + mode: realtime +``` + +### 2. Start Proxy + +```bash +litellm --config /path/to/config.yaml + +# RUNNING on http://0.0.0.0:4000 +``` + +### 3. Test Connection + +#### Python Client + +```python +import asyncio +import websockets +import json + +async def test_proxy(): + url = "ws://0.0.0.0:4000/v1/realtime?model=grok-voice-agent" + + async with websockets.connect( + url, + extra_headers={ + "Authorization": "Bearer sk-1234", # Your LiteLLM proxy key + "OpenAI-Beta": "realtime=v1" + } + ) as ws: + # Wait for conversation.created event from xAI + message = await ws.recv() + print(f"Connected: {message}") + + # Send a message + await ws.send(json.dumps({ + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [{ + "type": "input_text", + "text": "Hello from LiteLLM proxy!" + }] + } + })) + + # Request response + await ws.send(json.dumps({ + "type": "response.create" + })) + + # Listen for response + async for message in ws: + data = json.loads(message) + print(f"Event: {data['type']}") + + if data['type'] == 'response.done': + break + +asyncio.run(test_proxy()) +``` + +#### Node.js Client + +```javascript +// test.js - Run with: node test.js +const WebSocket = require("ws"); + +const url = "ws://0.0.0.0:4000/v1/realtime?model=grok-voice-agent"; + +const ws = new WebSocket(url, { + headers: { + "Authorization": "Bearer sk-1234", + "OpenAI-Beta": "realtime=v1", + }, +}); + +ws.on("open", function open() { + console.log("Connected to xAI via LiteLLM proxy"); + + // Send a message + ws.send(JSON.stringify({ + type: "conversation.item.create", + item: { + type: "message", + role: "user", + content: [{ + type: "input_text", + text: "What's the weather like?" + }] + } + })); + + // Request response + ws.send(JSON.stringify({ + type: "response.create", + response: { + modalities: ["text"], + instructions: "Please assist the user." + } + })); +}); + +ws.on("message", function incoming(message) { + const data = JSON.parse(message.toString()); + console.log(`Event: ${data.type}`); + + if (data.type === 'response.done') { + ws.close(); + } +}); + +ws.on("error", function handleError(error) { + console.error("Error: ", error); +}); +``` + +## Key Differences from OpenAI + +xAI's Grok Voice Agent has some differences from OpenAI's Realtime API: + +| Feature | xAI | OpenAI | LiteLLM Handling | +|---------|-----|--------|------------------| +| Initial Event | `conversation.created` | `session.created` | ⚠️ Passed through as-is | +| WebSocket URL | `wss://api.x.ai/v1/realtime` | `wss://api.openai.com/v1/realtime` | ✅ Auto-configured | +| Model | `grok-4-1-fast-non-reasoning` | `gpt-4o-realtime-preview` | ✅ Via model prefix | +| Audio Format | PCM16 24kHz mono | PCM16 24kHz mono | ✅ Compatible | +| Context Window | 2M tokens | 128K tokens | N/A | + +**What LiteLLM Handles:** +- ✅ Automatic URL routing to correct provider +- ✅ Authentication headers (no `OpenAI-Beta` header for xAI) +- ✅ WebSocket connection management +- ✅ All other event types are compatible + +**What You Need to Handle:** +- ⚠️ Initial event type difference (`conversation.created` vs `session.created`) + +**Tip:** Make your client compatible with both event types: +```python +# Handle both providers +if event['type'] in ['session.created', 'conversation.created']: + print("Connection established") +``` + +## Related Documentation + +- [xAI Chat/Text Models](/docs/providers/xai) +- [LiteLLM Realtime API Overview](/docs/realtime) +- [xAI Official Documentation](https://docs.x.ai/docs) + +## Support + +For issues or questions: +- [LiteLLM GitHub Issues](https://github.com/BerriAI/litellm/issues) +- [xAI Documentation](https://docs.x.ai/docs) diff --git a/docs/my-website/docs/proxy/admin_ui_sso.md b/docs/my-website/docs/proxy/admin_ui_sso.md index 7b299429db7..37e45b50284 100644 --- a/docs/my-website/docs/proxy/admin_ui_sso.md +++ b/docs/my-website/docs/proxy/admin_ui_sso.md @@ -23,26 +23,75 @@ From v1.76.0, SSO is now Free for up to 5 users. -1. Add Okta credentials to your .env +#### Step 1: Create an OIDC Application in Okta + +In your Okta Admin Console, create a new **OIDC Web Application**. See [Okta's guide on creating OIDC app integrations](https://help.okta.com/en-us/content/topics/apps/apps_app_integration_wizard_oidc.htm) for detailed instructions. + +When configuring the application: +- **Sign-in redirect URI**: `https:///sso/callback` +- **Sign-out redirect URI** (optional): `https://` + + + +After creating the app, copy your **Client ID** and **Client Secret** from the application's General tab: + + + +#### Step 2: Assign Users to the Application + +Ensure users are assigned to the app in the **Assignments** tab. If Federation Broker Mode is enabled, you may need to disable it to assign users manually. + +#### Step 3: Configure Authorization Server Access Policy + +:::warning Important +This step is required. Without an Access Policy for your app, users will get a `no_matching_policy` error when attempting to log in. +::: + +1. Go to **Security** → **API** + + + +2. Select the **default** authorization server (or your custom one) + + + +3. Click on **Access Policies** tab, create a new policy assigned to your LiteLLM app +4. Add a rule that allows the **Authorization Code** grant type + + + +See [Okta's Access Policy documentation](https://help.okta.com/en-us/content/topics/security/api-access-management/access-policies.htm) for more details. + +#### Step 4: Configure LiteLLM Environment Variables ```bash -GENERIC_CLIENT_ID = "" -GENERIC_CLIENT_SECRET = "" -GENERIC_AUTHORIZATION_ENDPOINT = "/authorize" # https://dev-2kqkcd6lx6kdkuzt.us.auth0.com/authorize -GENERIC_TOKEN_ENDPOINT = "/token" # https://dev-2kqkcd6lx6kdkuzt.us.auth0.com/oauth/token -GENERIC_USERINFO_ENDPOINT = "/userinfo" # https://dev-2kqkcd6lx6kdkuzt.us.auth0.com/userinfo -GENERIC_CLIENT_STATE = "random-string" # [OPTIONAL] REQUIRED BY OKTA, if not set random state value is generated -GENERIC_SSO_HEADERS = "Content-Type=application/json, X-Custom-Header=custom-value" # [OPTIONAL] Comma-separated list of additional headers to add to the request - e.g. Content-Type=application/json, etc. +GENERIC_CLIENT_ID="" +GENERIC_CLIENT_SECRET="" +GENERIC_AUTHORIZATION_ENDPOINT="https:///oauth2/default/v1/authorize" +GENERIC_TOKEN_ENDPOINT="https:///oauth2/default/v1/token" +GENERIC_USERINFO_ENDPOINT="https:///oauth2/default/v1/userinfo" +GENERIC_CLIENT_STATE="random-string" +PROXY_BASE_URL="https://" ``` -You can get your domain specific auth/token/userinfo endpoints at `/.well-known/openid-configuration` +:::tip +You can find all OAuth endpoints at `https:///.well-known/openid-configuration` +::: -2. Add proxy url as callback_url on Okta +#### Step 5: Test the SSO Flow -On Okta, add the 'callback_url' as `/sso/callback` +1. Start your LiteLLM proxy +2. Navigate to `https:///ui` +3. Click the SSO login button +4. Authenticate with Okta and verify you're redirected back to LiteLLM +#### Troubleshooting - +| Error | Cause | Solution | +|-------|-------|----------| +| `redirect_uri` error | Redirect URI not configured | Add `/sso/callback` to Sign-in redirect URIs in Okta | +| `access_denied` | User not assigned to app | Assign the user in the Assignments tab | +| `no_matching_policy` | Missing Access Policy | Create an Access Policy in the Authorization Server (see Step 3) | diff --git a/docs/my-website/docs/proxy/cli.md b/docs/my-website/docs/proxy/cli.md index 9244f75b756..d3624000a32 100644 --- a/docs/my-website/docs/proxy/cli.md +++ b/docs/my-website/docs/proxy/cli.md @@ -1,7 +1,10 @@ # CLI Arguments -Cli arguments, --host, --port, --num_workers -## --host +This page documents all command-line interface (CLI) arguments available for the LiteLLM proxy server. + +## Server Configuration + +### --host - **Default:** `'0.0.0.0'` - The host for the server to listen on. - **Usage:** @@ -14,7 +17,7 @@ Cli arguments, --host, --port, --num_workers litellm ``` -## --port +### --port - **Default:** `4000` - The port to bind the server to. - **Usage:** @@ -27,9 +30,9 @@ Cli arguments, --host, --port, --num_workers litellm ``` -## --num_workers - - **Default:** `1` - - The number of uvicorn workers to spin up. +### --num_workers + - **Default:** Number of logical CPUs in the system, or `4` if that cannot be determined + - The number of uvicorn / gunicorn workers to spin up. - **Usage:** ```shell litellm --num_workers 4 @@ -40,83 +43,183 @@ Cli arguments, --host, --port, --num_workers litellm ``` -## --api_base +### --config + - **Short form:** `-c` - **Default:** `None` - - The API base for the model litellm should call. + - Path to the proxy configuration file (e.g., config.yaml). - **Usage:** ```shell - litellm --model huggingface/tinyllama --api_base https://k58ory32yinf1ly0.us-east-1.aws.endpoints.huggingface.cloud + litellm --config path/to/config.yaml ``` -## --api_version +### --log_config - **Default:** `None` - - For Azure services, specify the API version. + - **Type:** `str` + - Path to the logging configuration file for uvicorn. - **Usage:** ```shell - litellm --model azure/gpt-deployment --api_version 2023-08-01 --api_base https://" + litellm --log_config path/to/log_config.conf ``` -## --model or -m +### --keepalive_timeout - **Default:** `None` - - The model name to pass to Litellm. + - **Type:** `int` + - Set the uvicorn keepalive timeout in seconds (uvicorn timeout_keep_alive parameter). - **Usage:** ```shell - litellm --model gpt-3.5-turbo + litellm --keepalive_timeout 30 ``` + - **Usage - set Environment Variable:** `KEEPALIVE_TIMEOUT` + ```shell + export KEEPALIVE_TIMEOUT=30 + litellm + ``` -## --test - - **Type:** `bool` (Flag) - - Proxy chat completions URL to make a test request. +### --max_requests_before_restart + - **Default:** `None` + - **Type:** `int` + - Restart worker after this many requests. This is useful for mitigating memory growth over time. + - For uvicorn: maps to `limit_max_requests` + - For gunicorn: maps to `max_requests` - **Usage:** ```shell - litellm --test + litellm --max_requests_before_restart 10000 ``` + - **Usage - set Environment Variable:** `MAX_REQUESTS_BEFORE_RESTART` + ```shell + export MAX_REQUESTS_BEFORE_RESTART=10000 + litellm + ``` + +## Server Backend Options -## --health +### --run_gunicorn + - **Default:** `False` - **Type:** `bool` (Flag) - - Runs a health check on all models in config.yaml + - Starts proxy via gunicorn instead of uvicorn. Better for managing multiple workers in production. - **Usage:** ```shell - litellm --health + litellm --run_gunicorn ``` -## --alias - - **Default:** `None` - - An alias for the model, for user-friendly reference. +### --run_hypercorn + - **Default:** `False` + - **Type:** `bool` (Flag) + - Starts proxy via hypercorn instead of uvicorn. Supports HTTP/2. - **Usage:** ```shell - litellm --alias my-gpt-model + litellm --run_hypercorn ``` -## --debug +### --skip_server_startup - **Default:** `False` - **Type:** `bool` (Flag) - - Enable debugging mode for the input. + - Skip starting the server after setup (useful for database migrations only). - **Usage:** ```shell - litellm --debug + litellm --skip_server_startup ``` - - **Usage - set Environment Variable:** `DEBUG` + +## SSL/TLS Configuration + +### --ssl_keyfile_path + - **Default:** `None` + - **Type:** `str` + - Path to the SSL keyfile. Use this when you want to provide SSL certificate when starting proxy. + - **Usage:** + ```shell + litellm --ssl_keyfile_path /path/to/key.pem --ssl_certfile_path /path/to/cert.pem + ``` + - **Usage - set Environment Variable:** `SSL_KEYFILE_PATH` ```shell - export DEBUG=True + export SSL_KEYFILE_PATH=/path/to/key.pem litellm ``` -## --detailed_debug - - **Default:** `False` - - **Type:** `bool` (Flag) - - Enable debugging mode for the input. +### --ssl_certfile_path + - **Default:** `None` + - **Type:** `str` + - Path to the SSL certfile. Use this when you want to provide SSL certificate when starting proxy. - **Usage:** ```shell - litellm --detailed_debug + litellm --ssl_certfile_path /path/to/cert.pem --ssl_keyfile_path /path/to/key.pem ``` - - **Usage - set Environment Variable:** `DETAILED_DEBUG` + - **Usage - set Environment Variable:** `SSL_CERTFILE_PATH` ```shell - export DETAILED_DEBUG=True + export SSL_CERTFILE_PATH=/path/to/cert.pem litellm ``` -#### --temperature +### --ciphers + - **Default:** `None` + - **Type:** `str` + - Ciphers to use for the SSL setup. Only used with `--run_hypercorn`. + - **Usage:** + ```shell + litellm --run_hypercorn --ssl_keyfile_path /path/to/key.pem --ssl_certfile_path /path/to/cert.pem --ciphers "ECDHE+AESGCM" + ``` + +## Model Configuration + +### --model or -m + - **Default:** `None` + - The model name to pass to LiteLLM. + - **Usage:** + ```shell + litellm --model gpt-3.5-turbo + ``` + +### --alias + - **Default:** `None` + - An alias for the model, for user-friendly reference. Use this to give a litellm model name (e.g., "huggingface/codellama/CodeLlama-7b-Instruct-hf") a more user-friendly name ("codellama"). + - **Usage:** + ```shell + litellm --alias my-gpt-model + ``` + +### --api_base + - **Default:** `None` + - The API base for the model LiteLLM should call. + - **Usage:** + ```shell + litellm --model huggingface/tinyllama --api_base https://k58ory32yinf1ly0.us-east-1.aws.endpoints.huggingface.cloud + ``` + +### --api_version + - **Default:** `2024-07-01-preview` + - For Azure services, specify the API version. + - **Usage:** + ```shell + litellm --model azure/gpt-deployment --api_version 2023-08-01 --api_base https://" + ``` + +### --headers + - **Default:** `None` + - Headers for the API call (as JSON string). + - **Usage:** + ```shell + litellm --model my-model --headers '{"Authorization": "Bearer token"}' + ``` + +### --add_key + - **Default:** `None` + - Add a key to the model configuration. + - **Usage:** + ```shell + litellm --add_key my-api-key + ``` + +### --save + - **Type:** `bool` (Flag) + - Save the model-specific config. + - **Usage:** + ```shell + litellm --model gpt-3.5-turbo --save + ``` + +## Model Parameters + +### --temperature - **Default:** `None` - **Type:** `float` - Set the temperature for the model. @@ -125,7 +228,7 @@ Cli arguments, --host, --port, --num_workers litellm --temperature 0.7 ``` -## --max_tokens +### --max_tokens - **Default:** `None` - **Type:** `int` - Set the maximum number of tokens for the model output. @@ -134,8 +237,8 @@ Cli arguments, --host, --port, --num_workers litellm --max_tokens 50 ``` -## --request_timeout - - **Default:** `6000` +### --request_timeout + - **Default:** `None` - **Type:** `int` - Set the timeout in seconds for completion calls. - **Usage:** @@ -143,7 +246,16 @@ Cli arguments, --host, --port, --num_workers litellm --request_timeout 300 ``` -## --drop_params +### --max_budget + - **Default:** `None` + - **Type:** `float` + - Set max budget for API calls. Works for hosted models like OpenAI, TogetherAI, Anthropic, etc. + - **Usage:** + ```shell + litellm --max_budget 100.0 + ``` + +### --drop_params - **Type:** `bool` (Flag) - Drop any unmapped params. - **Usage:** @@ -151,7 +263,7 @@ Cli arguments, --host, --port, --num_workers litellm --drop_params ``` -## --add_function_to_prompt +### --add_function_to_prompt - **Type:** `bool` (Flag) - If a function passed but unsupported, pass it as a part of the prompt. - **Usage:** @@ -159,37 +271,142 @@ Cli arguments, --host, --port, --num_workers litellm --add_function_to_prompt ``` -## --config - - Configure Litellm by providing a configuration file path. +## Database Configuration + +### --iam_token_db_auth + - **Default:** `False` + - **Type:** `bool` (Flag) + - Connects to an RDS database using IAM token authentication instead of a password. This is useful for AWS RDS instances that are configured to use IAM database authentication. + - When enabled, LiteLLM will generate an IAM authentication token to connect to the database. + - **Required Environment Variables:** + - `DATABASE_HOST` - The RDS database host + - `DATABASE_PORT` - The database port + - `DATABASE_USER` - The database user + - `DATABASE_NAME` - The database name + - `DATABASE_SCHEMA` (optional) - The database schema - **Usage:** ```shell - litellm --config path/to/config.yaml + litellm --iam_token_db_auth + ``` + - **Usage - set Environment Variable:** `IAM_TOKEN_DB_AUTH` + ```shell + export IAM_TOKEN_DB_AUTH=True + export DATABASE_HOST=mydb.us-east-1.rds.amazonaws.com + export DATABASE_PORT=5432 + export DATABASE_USER=mydbuser + export DATABASE_NAME=mydb + litellm ``` -## --telemetry - - **Default:** `True` - - **Type:** `bool` - - Help track usage of this feature. +### --use_prisma_db_push + - **Default:** `False` + - **Type:** `bool` (Flag) + - Use `prisma db push` instead of `prisma migrate` for database schema updates. This is useful when you want to quickly sync your database schema without creating migration files. - **Usage:** ```shell - litellm --telemetry False + litellm --use_prisma_db_push ``` +## Debugging -## --log_config - - **Default:** `None` - - **Type:** `str` - - Specify a log configuration file for uvicorn. +### --debug + - **Default:** `False` + - **Type:** `bool` (Flag) + - Enable debugging mode for the input. - **Usage:** ```shell - litellm --log_config path/to/log_config.conf + litellm --debug ``` + - **Usage - set Environment Variable:** `DEBUG` + ```shell + export DEBUG=True + litellm + ``` -## --skip_server_startup +### --detailed_debug - **Default:** `False` - **Type:** `bool` (Flag) - - Skip starting the server after setup (useful for DB migrations only). + - Enable detailed debugging mode to view verbose debug logs. - **Usage:** ```shell - litellm --skip_server_startup - ``` \ No newline at end of file + litellm --detailed_debug + ``` + - **Usage - set Environment Variable:** `DETAILED_DEBUG` + ```shell + export DETAILED_DEBUG=True + litellm + ``` + +### --local + - **Default:** `False` + - **Type:** `bool` (Flag) + - For local debugging purposes. + - **Usage:** + ```shell + litellm --local + ``` + +## Testing & Health Checks + +### --test + - **Type:** `bool` (Flag) + - Proxy chat completions URL to make a test request to. + - **Usage:** + ```shell + litellm --test + ``` + +### --test_async + - **Default:** `False` + - **Type:** `bool` (Flag) + - Calls async endpoints `/queue/requests` and `/queue/response`. + - **Usage:** + ```shell + litellm --test_async + ``` + +### --num_requests + - **Default:** `10` + - **Type:** `int` + - Number of requests to hit async endpoint with (used with `--test_async`). + - **Usage:** + ```shell + litellm --test_async --num_requests 100 + ``` + +### --health + - **Type:** `bool` (Flag) + - Runs a health check on all models in config.yaml. + - **Usage:** + ```shell + litellm --health + ``` + +## Other Options + +### --version + - **Short form:** `-v` + - **Type:** `bool` (Flag) + - Print LiteLLM version and exit. + - **Usage:** + ```shell + litellm --version + ``` + +### --telemetry + - **Default:** `True` + - **Type:** `bool` + - Help track usage of this feature. Turn off for privacy. + - **Usage:** + ```shell + litellm --telemetry False + ``` + +### --use_queue + - **Default:** `False` + - **Type:** `bool` (Flag) + - To use celery workers for async endpoints. + - **Usage:** + ```shell + litellm --use_queue + ``` diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md index bb2c7e01c80..5cdae51f448 100644 --- a/docs/my-website/docs/proxy/config_settings.md +++ b/docs/my-website/docs/proxy/config_settings.md @@ -94,7 +94,7 @@ litellm_settings: # /chat/completions, /completions, /embeddings, /audio/transcriptions mode: default_off # if default_off, you need to opt in to caching on a per call basis ttl: 600 # ttl for caching - disable_copilot_system_to_assistant: False # If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior. + disable_copilot_system_to_assistant: False # DEPRECATED - GitHub Copilot API supports system prompts. callback_settings: otel: @@ -197,7 +197,7 @@ router_settings: | disable_add_transform_inline_image_block | boolean | For Fireworks AI models - if true, turns off the auto-add of `#transform=inline` to the url of the image_url, if the model is not a vision model. | | disable_hf_tokenizer_download | boolean | If true, it defaults to using the openai tokenizer for all models (including huggingface models). | | enable_json_schema_validation | boolean | If true, enables json schema validation for all requests. | -| disable_copilot_system_to_assistant | boolean | If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior. Useful for tools (like Claude Code) that send system messages, which Copilot does not support. | +| disable_copilot_system_to_assistant | boolean | **DEPRECATED** - GitHub Copilot API supports system prompts. | ### general_settings - Reference @@ -321,6 +321,7 @@ router_settings: | redis_host | string | The host address for the Redis server. **Only set this if you have multiple instances of LiteLLM Proxy and want current tpm/rpm tracking to be shared across them** | | redis_password | string | The password for the Redis server. **Only set this if you have multiple instances of LiteLLM Proxy and want current tpm/rpm tracking to be shared across them** | | redis_port | string | The port number for the Redis server. **Only set this if you have multiple instances of LiteLLM Proxy and want current tpm/rpm tracking to be shared across them**| +| redis_db | int | The database number for the Redis server. **Only set this if you have multiple instances of LiteLLM Proxy and want current tpm/rpm tracking to be shared across them**| | enable_pre_call_check | boolean | If true, checks if a call is within the model's context window before making the call. [More information here](reliability) | | content_policy_fallbacks | array of objects | Specifies fallback models for content policy violations. [More information here](reliability) | | fallbacks | array of objects | Specifies fallback models for all types of errors. [More information here](reliability) | @@ -544,6 +545,9 @@ router_settings: | DEFAULT_MAX_TOKENS | Default maximum tokens for LLM calls. Default is 4096 | DEFAULT_MAX_TOKENS_FOR_TRITON | Default maximum tokens for Triton models. Default is 2000 | DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE | Default maximum size for redis batch cache. Default is 1000 +| DEFAULT_MCP_SEMANTIC_FILTER_EMBEDDING_MODEL | Default embedding model for MCP semantic tool filtering. Default is "text-embedding-3-small" +| DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_THRESHOLD | Default similarity threshold for MCP semantic tool filtering. Default is 0.3 +| DEFAULT_MCP_SEMANTIC_FILTER_TOP_K | Default number of top results to return for MCP semantic tool filtering. Default is 10 | DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT | Default token count for mock response completions. Default is 20 | DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT | Default token count for mock response prompts. Default is 10 | DEFAULT_MODEL_CREATED_AT_TIME | Default creation timestamp for models. Default is 1677610602 @@ -801,6 +805,7 @@ router_settings: | MAXIMUM_TRACEBACK_LINES_TO_LOG | Maximum number of lines to log in traceback in LiteLLM Logs UI. Default is 100 | MAX_RETRY_DELAY | Maximum delay in seconds for retrying requests. Default is 8.0 | MAX_LANGFUSE_INITIALIZED_CLIENTS | Maximum number of Langfuse clients to initialize on proxy. Default is 50. This is set since langfuse initializes 1 thread everytime a client is initialized. We've had an incident in the past where we reached 100% cpu utilization because Langfuse was initialized several times. +| MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH | Maximum header length for MCP semantic filter tools. Default is 150 | MIN_NON_ZERO_TEMPERATURE | Minimum non-zero temperature value. Default is 0.0001 | MINIMUM_PROMPT_CACHE_TOKEN_COUNT | Minimum token count for caching a prompt. Default is 1024 | MISTRAL_API_BASE | Base URL for Mistral API. Default is https://api.mistral.ai diff --git a/docs/my-website/docs/proxy/custom_pricing.md b/docs/my-website/docs/proxy/custom_pricing.md index 8f4a4c450f5..b61da85bb1d 100644 --- a/docs/my-website/docs/proxy/custom_pricing.md +++ b/docs/my-website/docs/proxy/custom_pricing.md @@ -9,6 +9,7 @@ LiteLLM provides flexible cost tracking and pricing customization for all LLM pr - **Custom Pricing** - Override default model costs or set pricing for custom models - **Cost Per Token** - Track costs based on input/output tokens (most common) - **Cost Per Second** - Track costs based on runtime (e.g., Sagemaker) +- **Zero-Cost Models** - Bypass budget checks for free/on-premises models by setting costs to 0 - **[Provider Discounts](./provider_discounts.md)** - Apply percentage-based discounts to specific providers - **[Provider Margins](./provider_margins.md)** - Add fees/margins to LLM costs for internal billing - **Base Model Mapping** - Ensure accurate cost tracking for Azure deployments @@ -106,6 +107,51 @@ There are other keys you can use to specify costs for different scenarios and mo These keys evolve based on how new models handle multimodality. The latest version can be found at [https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json). +## Zero-Cost Models (Bypass Budget Checks) + +**Use Case**: You have on-premises or free models that should be accessible even when users exceed their budget limits. + +**Solution** ✅: Set both `input_cost_per_token` and `output_cost_per_token` to `0` (explicitly) to bypass all budget checks for that model. + +:::info + +When a model is configured with zero cost, LiteLLM will automatically skip ALL budget checks (user, team, team member, end-user, organization, and global proxy budget) for requests to that model. + +**Important**: Both costs must be **explicitly set to 0**. If costs are `null` or undefined, the model will be treated as having cost and budget checks will apply. + +::: + +### Configuration Example + +```yaml +model_list: + # On-premises model - free to use + - model_name: on-prem-llama + litellm_params: + model: ollama/llama3 + api_base: http://localhost:11434 + model_info: + input_cost_per_token: 0 # 👈 Explicitly set to 0 + output_cost_per_token: 0 # 👈 Explicitly set to 0 + + # Paid cloud model - budget checks apply + - model_name: gpt-4 + litellm_params: + model: gpt-4 + api_key: os.environ/OPENAI_API_KEY + # No model_info - uses default pricing from cost map +``` + +### Behavior + +With the above configuration: + +- **User over budget** → Can still use `on-prem-llama` ✅, but blocked from `gpt-4` ❌ +- **Team over budget** → Can still use `on-prem-llama` ✅, but blocked from `gpt-4` ❌ +- **End-user over budget** → Can still use `on-prem-llama` ✅, but blocked from `gpt-4` ❌ + +This ensures your free/on-premises models remain accessible regardless of budget constraints, while paid models are still properly governed. + ## Set 'base_model' for Cost Tracking (e.g. Azure deployments) **Problem**: Azure returns `gpt-4` in the response when `azure/gpt-4-1106-preview` is used. This leads to inaccurate cost tracking diff --git a/docs/my-website/docs/proxy/guardrails/custom_code_guardrail.md b/docs/my-website/docs/proxy/guardrails/custom_code_guardrail.md new file mode 100644 index 00000000000..8cbc247ae5e --- /dev/null +++ b/docs/my-website/docs/proxy/guardrails/custom_code_guardrail.md @@ -0,0 +1,332 @@ +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# Custom Code Guardrail + +Write custom guardrail logic using Python-like code that runs in a sandboxed environment. + +## Quick Start + +### 1. Define the guardrail in config + +```yaml +model_list: + - model_name: gpt-4 + litellm_params: + model: gpt-4 + api_key: os.environ/OPENAI_API_KEY + +guardrails: + - guardrail_name: block-ssn + litellm_params: + guardrail: custom_code + mode: pre_call + custom_code: | + def apply_guardrail(inputs, request_data, input_type): + for text in inputs["texts"]: + if regex_match(text, r"\d{3}-\d{2}-\d{4}"): + return block("SSN detected") + return allow() +``` + +### 2. Start proxy + +```bash +litellm --config config.yaml +``` + +### 3. Test + +```bash +curl -X POST http://localhost:4000/chat/completions \ + -H "Authorization: Bearer sk-1234" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gpt-4", + "messages": [{"role": "user", "content": "My SSN is 123-45-6789"}], + "guardrails": ["block-ssn"] + }' +``` + +## Configuration + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `guardrail` | string | ✅ | Must be `custom_code` | +| `mode` | string | ✅ | When to run: `pre_call`, `post_call`, `during_call` | +| `custom_code` | string | ✅ | Python-like code with `apply_guardrail` function | +| `default_on` | bool | ❌ | Run on all requests (default: `false`) | + +## Writing Custom Code + +### Function Signature + +Your code must define an `apply_guardrail` function. It can be either sync or async: + +```python +# Sync version +def apply_guardrail(inputs, request_data, input_type): + # inputs: see table below + # request_data: {"model": "...", "user_id": "...", "team_id": "...", "metadata": {...}} + # input_type: "request" or "response" + + return allow() # or block() or modify() + +# Async version (recommended when using HTTP primitives) +async def apply_guardrail(inputs, request_data, input_type): + response = await http_post("https://api.example.com/check", body={"text": inputs["texts"][0]}) + if response["success"] and response["body"].get("flagged"): + return block("Content flagged") + return allow() +``` + +### `inputs` Parameter + +| Field | Type | Description | +|-------|------|-------------| +| `texts` | `List[str]` | Extracted text from the request/response | +| `images` | `List[str]` | Extracted images (for image guardrails) | +| `tools` | `List[dict]` | Tools sent to the LLM | +| `tool_calls` | `List[dict]` | Tool calls returned from the LLM | +| `structured_messages` | `List[dict]` | Full messages with role info (system/user/assistant) | +| `model` | `str` | The model being used | + +### `request_data` Parameter + +| Field | Type | Description | +|-------|------|-------------| +| `model` | `str` | Model name | +| `user_id` | `str` | User ID from API key | +| `team_id` | `str` | Team ID from API key | +| `end_user_id` | `str` | End user ID | +| `metadata` | `dict` | Request metadata | + +### Return Values + +| Function | Description | +|----------|-------------| +| `allow()` | Let request/response through | +| `block(reason)` | Reject with message | +| `modify(texts=[], images=[], tool_calls=[])` | Transform content | + +## Built-in Primitives + +### Regex + +| Function | Description | +|----------|-------------| +| `regex_match(text, pattern)` | Returns `True` if pattern found | +| `regex_replace(text, pattern, replacement)` | Replace all matches | +| `regex_find_all(text, pattern)` | Return list of matches | + +### JSON + +| Function | Description | +|----------|-------------| +| `json_parse(text)` | Parse JSON string, returns `None` on error | +| `json_stringify(obj)` | Convert to JSON string | +| `json_schema_valid(obj, schema)` | Validate against JSON schema | + +### URL + +| Function | Description | +|----------|-------------| +| `extract_urls(text)` | Extract all URLs from text | +| `is_valid_url(url)` | Check if URL is valid | +| `all_urls_valid(text)` | Check all URLs in text are valid | + +### Code Detection + +| Function | Description | +|----------|-------------| +| `detect_code(text)` | Returns `True` if code detected | +| `detect_code_languages(text)` | Returns list of detected languages | +| `contains_code_language(text, ["sql", "python"])` | Check for specific languages | + +### Text Utilities + +| Function | Description | +|----------|-------------| +| `contains(text, substring)` | Check if substring exists | +| `contains_any(text, [substr1, substr2])` | Check if any substring exists | +| `word_count(text)` | Count words | +| `char_count(text)` | Count characters | +| `lower(text)` / `upper(text)` / `trim(text)` | String transforms | + +### HTTP Requests (Async) + +Make async HTTP requests to external APIs for additional validation or content moderation. + +| Function | Description | +|----------|-------------| +| `await http_request(url, method, headers, body, timeout)` | General async HTTP request | +| `await http_get(url, headers, timeout)` | Async GET request | +| `await http_post(url, body, headers, timeout)` | Async POST request | + +**Response format:** +```python +{ + "status_code": 200, # HTTP status code + "body": {...}, # Response body (parsed JSON or string) + "headers": {...}, # Response headers + "success": True, # True if status code is 2xx + "error": None # Error message if request failed +} +``` + +**Note:** When using HTTP primitives, define your function as `async def apply_guardrail(...)` for non-blocking execution. + +## Examples + +### Block PII (SSN) + +```python +def apply_guardrail(inputs, request_data, input_type): + for text in inputs["texts"]: + if regex_match(text, r"\d{3}-\d{2}-\d{4}"): + return block("SSN detected") + return allow() +``` + +### Redact Email Addresses + +```python +def apply_guardrail(inputs, request_data, input_type): + pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" + modified = [] + for text in inputs["texts"]: + modified.append(regex_replace(text, pattern, "[EMAIL REDACTED]")) + return modify(texts=modified) +``` + +### Block SQL Injection + +```python +def apply_guardrail(inputs, request_data, input_type): + if input_type != "request": + return allow() + for text in inputs["texts"]: + if contains_code_language(text, ["sql"]): + return block("SQL code not allowed") + return allow() +``` + +### Validate JSON Response + +```python +def apply_guardrail(inputs, request_data, input_type): + if input_type != "response": + return allow() + + schema = { + "type": "object", + "required": ["name", "value"] + } + + for text in inputs["texts"]: + obj = json_parse(text) + if obj is None: + return block("Invalid JSON response") + if not json_schema_valid(obj, schema): + return block("Response missing required fields") + return allow() +``` + +### Check URLs in Response + +```python +def apply_guardrail(inputs, request_data, input_type): + if input_type != "response": + return allow() + for text in inputs["texts"]: + if not all_urls_valid(text): + return block("Response contains invalid URLs") + return allow() +``` + +### Call External Moderation API (Async) + +```python +async def apply_guardrail(inputs, request_data, input_type): + # Call an external moderation API + for text in inputs["texts"]: + response = await http_post( + "https://api.example.com/moderate", + body={"text": text, "user_id": request_data["user_id"]}, + headers={"Authorization": "Bearer YOUR_API_KEY"}, + timeout=10 + ) + + if not response["success"]: + # API call failed - decide whether to allow or block + return allow() + + if response["body"].get("flagged"): + return block(response["body"].get("reason", "Content flagged")) + + return allow() +``` + +### Combine Multiple Checks + +```python +def apply_guardrail(inputs, request_data, input_type): + modified = [] + + for text in inputs["texts"]: + # Redact SSN + text = regex_replace(text, r"\d{3}-\d{2}-\d{4}", "[SSN]") + # Redact credit cards + text = regex_replace(text, r"\d{16}", "[CARD]") + modified.append(text) + + # Block SQL in requests + if input_type == "request": + for text in inputs["texts"]: + if contains_code_language(text, ["sql"]): + return block("SQL injection blocked") + + return modify(texts=modified) +``` + +## Sandbox Restrictions + +Custom code runs in a restricted environment: + +- ❌ No `import` statements +- ❌ No file I/O +- ❌ No `exec()` or `eval()` +- ✅ HTTP requests via built-in `http_request`, `http_get`, `http_post` primitives +- ✅ Only LiteLLM-provided primitives available + +## Per-Request Usage + +Enable guardrail per request: + +```bash +curl -X POST http://localhost:4000/chat/completions \ + -H "Authorization: Bearer sk-1234" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gpt-4", + "messages": [{"role": "user", "content": "Hello"}], + "guardrails": ["block-ssn"] + }' +``` + +## Default On + +Run guardrail on all requests: + +```yaml +litellm_settings: + guardrails: + - guardrail_name: block-ssn + litellm_params: + guardrail: custom_code + mode: pre_call + default_on: true + custom_code: | + def apply_guardrail(inputs, request_data, input_type): + ... +``` diff --git a/docs/my-website/docs/proxy/guardrails/grayswan.md b/docs/my-website/docs/proxy/guardrails/grayswan.md index d6efaf15504..6c0ccbc293d 100644 --- a/docs/my-website/docs/proxy/guardrails/grayswan.md +++ b/docs/my-website/docs/proxy/guardrails/grayswan.md @@ -13,20 +13,26 @@ Cygnal returns a `violation` score between `0` and `1` (higher means more likely ### 1. Obtain Credentials -1. Create a Gray Swan account and generate a Cygnal API key. +1. Log in to our Gray Swan platform and generate a Cygnal API key. + + For existing customers, you should already have access to our [platform](https://platform.grayswan.ai). + + For new users, please register at this [page](https://hubs.ly/Q03-sX1J0) and we are more than happy to give you an onboarding! + + 2. Configure environment variables for the LiteLLM proxy host: -```bash -export GRAYSWAN_API_KEY="your-grayswan-key" -export GRAYSWAN_API_BASE="https://api.grayswan.ai" -``` + ```bash + export GRAYSWAN_API_KEY="your-grayswan-key" + export GRAYSWAN_API_BASE="https://api.grayswan.ai" + ``` ### 2. Configure `config.yaml` -Add a guardrail entry that references the Gray Swan integration. Below is a balanced example that monitors both input and output but only blocks once the violation score reaches the configured threshold. +Add a guardrail entry that references the Gray Swan integration. Below is our recommmended settings. ```yaml -model_list: +model_list: # this part is a standard litellm configuration for reference - model_name: openai/gpt-4.1-mini litellm_params: model: openai/gpt-4.1-mini @@ -40,13 +46,14 @@ guardrails: api_key: os.environ/GRAYSWAN_API_KEY api_base: os.environ/GRAYSWAN_API_BASE # optional optional_params: - on_flagged_action: monitor # or "block" + on_flagged_action: passthrough # or "block" or "monitor" violation_threshold: 0.5 # score >= threshold is flagged reasoning_mode: hybrid # off | hybrid | thinking - categories: - safety: "Detect jailbreaks and policy violations" - policy_id: "your-cygnal-policy-id" + policy_id: "your-cygnal-policy-id" # Optional: Your Cygnal policy ID. Defaults to a content safety policy if empty. + streaming_end_of_stream_only: true # For streaming API, only send the assembled message to Cygnal (post_call only). Defaults to false. default_on: true + guardrail_timeout: 30 # Defaults to 30 seconds. Change accordingly. + fail_open: true # Defaults to true; set to false to propagate guardrail errors. general_settings: master_key: "your-litellm-master-key" @@ -65,13 +72,13 @@ litellm --config config.yaml --port 4000 ## Choosing Guardrail Modes -Gray Swan can run during `pre_call`, `during_call`, and `post_call` stages. Combine modes based on your latency and coverage requirements. +Gray Swan can run during `pre_call`, `during_call`, and `post_call` stages. Combine modes based on your latency and coverage requirements. | Mode | When it Runs | Protects | Typical Use Case | |--------------|-------------------|-----------------------|------------------| | `pre_call` | Before LLM call | User input only | Block prompt injection before it reaches the model | | `during_call`| Parallel to call | User input only | Low-latency monitoring without blocking | -| `post_call` | After response | Full conversation | Scan output for policy violations, leaked secrets, or IPI | +| `post_call` | After response | Model Outputs | Scan output for policy violations, leaked secrets, or IPI | When using `during_call` with `on_flagged_action: block` or `on_flagged_action: passthrough`: @@ -81,87 +88,110 @@ When using `during_call` with `on_flagged_action: block` or `on_flagged_action: - The guardrail exception prevents the response from reaching the user, but **does not cancel the running LLM task** - This means you pay full LLM costs while returning an error/passthrough message to the user -**Recommendation:** For cost-sensitive applications, use `pre_call` and `post_call` instead of `during_call` for blocking or passthrough modes. Reserve `during_call` for `monitor` mode where you want low-latency logging without impacting the user experience. +**Recommendation:** Use `pre_call` and `post_call` instead of `during_call` for `passthrough` (or `block`) `on_flagged_action` (see our recommended configuration above). Reserve `during_call` for `monitor` mode ONLY when you want low-latency logging without impacting the user experience. - - +--- -```yaml -guardrails: - - guardrail_name: "cygnal-monitor-only" - litellm_params: - guardrail: grayswan - mode: "during_call" - api_key: os.environ/GRAYSWAN_API_KEY - optional_params: - on_flagged_action: monitor - violation_threshold: 0.6 - default_on: true -``` +## Work with Claude Code -Best for visibility without blocking. Alerts are logged via LiteLLM’s standard logging callbacks. +Follow the official litellm [guide](https://docs.litellm.ai/docs/tutorials/claude_responses_api) on setting up Claude Code with litellm, with the guardrail part mentioned above added to your litellm configuration. Cygnal natively supports coding agent policies defense. Define your own policy or use the provided coding policies on the platform. The example config we show above is also the recommended setup for Claude Code (with the `policy_id` replaced with an appropriate one). - - +--- -```yaml -guardrails: - - guardrail_name: "cygnal-block-input" - litellm_params: - guardrail: grayswan - mode: "pre_call" - api_key: os.environ/GRAYSWAN_API_KEY - optional_params: - on_flagged_action: block - violation_threshold: 0.4 - categories: - pii: "Detect sensitive data" - default_on: true -``` +## Per-request overrides via `extra_body` -Stops malicious or sensitive prompts before any tokens are generated. +You can override parts of the Gray Swan guardrail configuration on a per-request basis by passing `litellm_metadata.guardrails[*].grayswan.extra_body`. - - +`extra_body` is merged into the Cygnal request body and takes precedence over specific fields from `config.yaml`, which are `policy_id`, `violation_threshold`, and `reasoning_mode`. -```yaml -guardrails: - - guardrail_name: "cygnal-full-coverage" - litellm_params: - guardrail: grayswan - mode: [pre_call, post_call] - api_key: os.environ/GRAYSWAN_API_KEY - optional_params: - on_flagged_action: block - violation_threshold: 0.5 - reasoning_mode: thinking - policy_id: "policy-id-from-grayswan" - default_on: true -``` +If you include a `metadata` field inside `extra_body`, it is forwarded to the Cygnal API as-is under the request body's `metadata` field. -Provides the strongest enforcement by inspecting both prompts and responses. +Example: - - +```bash +curl -X POST "http://0.0.0.0:4000/v1/messages?beta=true" \ + -H "Authorization: Bearer token" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "openrouter/anthropic/claude-sonnet-4.5", + "messages": [{"role": "user", "content": "hello"}], + "litellm_metadata": { + "guardrails": [ + { + "cygnal-monitor": { + "extra_body": { + "policy_id": "specific policy id you want to use", + "metadata": { + "user": "health-check" + } + } + } + } + ] + } + }' +``` -```yaml -guardrails: - - guardrail_name: "cygnal-passthrough" - litellm_params: - guardrail: grayswan - mode: [pre_call, post_call] - api_key: os.environ/GRAYSWAN_API_KEY - optional_params: - on_flagged_action: passthrough - violation_threshold: 0.5 - default_on: true +OpenAI client: + +```python +from openai import OpenAI + +client = OpenAI(api_key="anything", base_url="http://0.0.0.0:4000") + +resp = client.responses.create( + model="openrouter/anthropic/claude-sonnet-4.5", + input="hello", + extra_body={ + "litellm_metadata": { + "guardrails": [ + { + "cygnal-monitor": { + "extra_body": { + "policy_id": "69038214e5cdb6befc5e991e", + "metadata": {"trace_id": "trace-123"}, + } + } + } + ] + } + }, +) +``` + +Anthropic client: + +```python +from anthropic import Anthropic + +client = Anthropic(api_key="anything", base_url="http://0.0.0.0:4000") + +resp = client.messages.create( + model="openrouter/anthropic/claude-sonnet-4.5", + max_tokens=256, + messages=[{"role": "user", "content": "hello"}], + extra_body={ + "litellm_metadata": { + "guardrails": [ + { + "cygnal-monitor": { + "extra_body": { + "policy_id": "69038214e5cdb6befc5e991e", + "metadata": {"trace_id": "trace-123"}, + } + } + } + ] + } + }, +) ``` -Allows requests to proceed without raising a 400 error when content is flagged. Instead of blocking, the model response content is replaced with a detailed violation message including violation score, violated rules, and detection flags (mutation, IPI). **Supported Response Formats:** OpenAI chat/text completions, Anthropic Messages API. Other response types (embeddings, images, etc.) will log a warning and return unchanged. +Notes: - - +- The guardrail name (for example, `cygnal-monitor`) must match the `guardrail_name` in `config.yaml`. +- Per-request guardrail overrides may require a premium license, depending on your proxy settings. --- @@ -170,9 +200,14 @@ Allows requests to proceed without raising a 400 error when content is flagged. | Parameter | Type | Description | |---------------------------------------|-----------------|-------------| | `api_key` | string | Gray Swan Cygnal API key. Reads from `GRAYSWAN_API_KEY` if omitted. | +| `api_base` | string | Override for the Gray Swan API base URL. Defaults to `https://api.grayswan.ai` or `GRAYSWAN_API_BASE`. | | `mode` | string or list | Guardrail stages (`pre_call`, `during_call`, `post_call`). | | `optional_params.on_flagged_action` | string | `monitor` (log only), `block` (raise `HTTPException`), or `passthrough` (replace response content with violation message, no 400 error). | -| `.optional_params.violation_threshold`| number (0-1) | Scores at or above this value are considered violations. | +| `optional_params.violation_threshold` | number (0-1) | Scores at or above this value are considered violations. | | `optional_params.reasoning_mode` | string | `off`, `hybrid`, or `thinking`. Enables Cygnal's reasoning capabilities. | | `optional_params.categories` | object | Map of custom category names to descriptions. | | `optional_params.policy_id` | string | Gray Swan policy identifier. | +| `guardrail_timeout` | number | Timeout in seconds for the Cygnal request. Defaults to 30. | +| `fail_open` | boolean | If true, errors contacting Cygnal are logged and the request proceeds; if false, errors propagate. Defaults to treu. | +| `streaming_end_of_stream_only` | boolean | For streaming `post_call`, only send the final assembled response to Cygnal. Defaults to false. | +| `default_on` | boolean | Run the guardrail on every request by default. | diff --git a/docs/my-website/docs/proxy/load_balancing.md b/docs/my-website/docs/proxy/load_balancing.md index 42f6ef1aa51..186307d6498 100644 --- a/docs/my-website/docs/proxy/load_balancing.md +++ b/docs/my-website/docs/proxy/load_balancing.md @@ -69,6 +69,67 @@ router_settings: redis_port: 1992 ``` +## Enforce Model Rate Limits + +Strictly enforce RPM/TPM limits set on deployments. When limits are exceeded, requests are blocked **before** reaching the LLM provider with a `429 Too Many Requests` error. + +:::info +By default, `rpm` and `tpm` values are only used for **routing decisions** (picking deployments with capacity). With `enforce_model_rate_limits`, they become **hard limits**. +::: + +### Quick Start + +```yaml +model_list: + - model_name: gpt-4 + litellm_params: + model: openai/gpt-4 + api_key: os.environ/OPENAI_API_KEY + rpm: 60 # 60 requests per minute + tpm: 90000 # 90k tokens per minute + +router_settings: + optional_pre_call_checks: + - enforce_model_rate_limits # 👈 Enables strict enforcement +``` + +### How It Works + +| Limit Type | Enforcement | Accuracy | +|------------|-------------|----------| +| **RPM** | Hard limit - blocked at exact threshold | 100% accurate | +| **TPM** | Best-effort - may slightly exceed | Blocked when already over limit | + +**Why TPM is best-effort:** Token count is unknown until the LLM responds. TPM is checked before each request (blocks if already over), and tracked after (adds actual tokens used). + +### Error Response + +```json +{ + "error": { + "message": "Model rate limit exceeded. RPM limit=60, current usage=60", + "type": "rate_limit_error", + "code": 429 + } +} +``` + +Response includes `retry-after: 60` header. + +### Multi-Instance Deployment + +For multiple LiteLLM proxy instances, add Redis to share rate limit state: + +```yaml +router_settings: + optional_pre_call_checks: + - enforce_model_rate_limits + redis_host: redis.example.com + redis_port: 6379 + redis_password: your-password +``` + + :::info Detailed information about [routing strategies can be found here](../routing) ::: diff --git a/docs/my-website/docs/proxy/request_tags.md b/docs/my-website/docs/proxy/request_tags.md new file mode 100644 index 00000000000..c78c48229b4 --- /dev/null +++ b/docs/my-website/docs/proxy/request_tags.md @@ -0,0 +1,58 @@ +# Request Tags for Spend Tracking + +Add tags to model deployments to track spend by environment, AWS account, or any custom label. + +Tags appear in the `request_tags` field of LiteLLM spend logs. + +## Config Setup + +Set tags on model deployments in `config.yaml`: + +```yaml title="config.yaml" +model_list: + - model_name: gpt-4 + litellm_params: + model: azure/gpt-4-prod + api_key: os.environ/AZURE_PROD_API_KEY + api_base: https://prod.openai.azure.com/ + tags: ["AWS_IAM_PROD"] # 👈 Tag for production + + - model_name: gpt-4-dev + litellm_params: + model: azure/gpt-4-dev + api_key: os.environ/AZURE_DEV_API_KEY + api_base: https://dev.openai.azure.com/ + tags: ["AWS_IAM_DEV"] # 👈 Tag for development +``` + +## Make Request + +Requests just specify the model - tags are automatically applied: + +```bash +curl -X POST 'http://0.0.0.0:4000/chat/completions' \ + -H 'Authorization: Bearer sk-1234' \ + -H 'Content-Type: application/json' \ + -d '{ + "model": "gpt-4", + "messages": [{"role": "user", "content": "Hello"}] + }' +``` + +## Spend Logs + +The tag from the model config appears in `LiteLLM_SpendLogs`: + +```json +{ + "request_id": "chatcmpl-abc123", + "request_tags": ["AWS_IAM_PROD"], + "spend": 0.002, + "model": "gpt-4" +} +``` + +## Related + +- [Spend Tracking Overview](cost_tracking.md) +- [Tag Budgets](tag_budgets.md) - Set budget limits per tag diff --git a/docs/my-website/docs/proxy/ui_logs.md b/docs/my-website/docs/proxy/ui_logs.md index b6d3d2ae7ca..8cfe818ebfd 100644 --- a/docs/my-website/docs/proxy/ui_logs.md +++ b/docs/my-website/docs/proxy/ui_logs.md @@ -37,6 +37,40 @@ general_settings: +## Tracing Tools + +View which tools were provided and called in your completion requests. + + + +**Example:** Make a completion request with tools: + +```bash +curl -X POST 'http://localhost:4000/chat/completions' \ + -H 'Authorization: Bearer sk-1234' \ + -H 'Content-Type: application/json' \ + -d '{ + "model": "gpt-4", + "messages": [{"role": "user", "content": "What is the weather?"}], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather", + "parameters": { + "type": "object", + "properties": { + "location": {"type": "string"} + } + } + } + } + ] + }' +``` + +Check the Logs page to see all tools provided and which ones were called. ## Stop storing Error Logs in DB diff --git a/docs/my-website/docs/realtime.md b/docs/my-website/docs/realtime.md index 0b3c823f5db..b191c82c670 100644 --- a/docs/my-website/docs/realtime.md +++ b/docs/my-website/docs/realtime.md @@ -3,13 +3,15 @@ import TabItem from '@theme/TabItem'; # /realtime -Use this to loadbalance across Azure + OpenAI. +Use this to loadbalance across Azure + OpenAI + xAI and more. Supported Providers: - OpenAI - Azure +- xAI ([see full docs](/docs/providers/xai_realtime)) - Google AI Studio (Gemini) - Vertex AI +- Bedrock ## Proxy Usage @@ -45,6 +47,21 @@ model_list: api_key: os.environ/OPENAI_API_KEY ``` + + + +```yaml +model_list: + - model_name: grok-voice-agent + litellm_params: + model: xai/grok-4-1-fast-non-reasoning + api_key: os.environ/XAI_API_KEY + model_info: + mode: realtime +``` + +**[See full xAI Realtime documentation →](/docs/providers/xai_realtime)** + diff --git a/docs/my-website/docs/routing.md b/docs/my-website/docs/routing.md index 2b3a28edf75..67e7f681147 100644 --- a/docs/my-website/docs/routing.md +++ b/docs/my-website/docs/routing.md @@ -1588,11 +1588,13 @@ Get a slack webhook url from https://api.slack.com/messaging/webhooks Initialize an `AlertingConfig` and pass it to `litellm.Router`. The following code will trigger an alert because `api_key=bad-key` which is invalid ```python -from litellm.router import AlertingConfig import litellm +from litellm.router import Router +from litellm.types.router import AlertingConfig import os +import asyncio -router = litellm.Router( +router = Router( model_list=[ { "model_name": "gpt-3.5-turbo", @@ -1603,17 +1605,28 @@ router = litellm.Router( } ], alerting_config= AlertingConfig( - alerting_threshold=10, # threshold for slow / hanging llm responses (in seconds). Defaults to 300 seconds - webhook_url= os.getenv("SLACK_WEBHOOK_URL") # webhook you want to send alerts to + alerting_threshold=10, + webhook_url= "https:/..." ), ) -try: - await router.acompletion( - model="gpt-3.5-turbo", - messages=[{"role": "user", "content": "Hey, how's it going?"}], - ) -except: - pass + +async def main(): + print(f"\n=== Configuration ===") + print(f"Slack logger exists: {router.slack_alerting_logger is not None}") + + try: + await router.acompletion( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hey, how's it going?"}], + ) + except Exception as e: + print(f"\n=== Exception caught ===") + print(f"Waiting 10 seconds for alerts to be sent via periodic flush...") + await asyncio.sleep(10) + print(f"\n=== After waiting ===") + print(f"Alert should have been sent to Slack!") + +asyncio.run(main()) ``` ## Track cost for Azure Deployments diff --git a/docs/my-website/docs/troubleshoot/prisma_migrations.md b/docs/my-website/docs/troubleshoot/prisma_migrations.md new file mode 100644 index 00000000000..9d9cb585b2b --- /dev/null +++ b/docs/my-website/docs/troubleshoot/prisma_migrations.md @@ -0,0 +1,113 @@ +# Troubleshooting Prisma Migration Errors + +Common Prisma migration issues encountered when upgrading or downgrading LiteLLM proxy versions, and how to fix them. + +## How Prisma Migrations Work in LiteLLM + +- LiteLLM uses [Prisma](https://www.prisma.io/) to manage its PostgreSQL database schema. +- Migration history is tracked in the `_prisma_migrations` table in your database. +- When LiteLLM starts, it runs `prisma migrate deploy` to apply any new migrations. +- Upgrading LiteLLM applies all migrations added since your last applied version. + +## Common Errors + +### 1. `relation "X" does not exist` + +**Example error:** + +``` +ERROR: relation "LiteLLM_DeletedTeamTable" does not exist +Migration: 20260116142756_update_deleted_keys_teams_table_routing_settings +``` + +**Cause:** This typically happens after a version rollback. The `_prisma_migrations` table still records migrations from the newer version as "applied," but the underlying database tables were modified, dropped, or never fully created. + +**How to fix:** + +#### Step 1 — Delete the failed migration entry and restart + +Remove the problematic migration from the history so it can be re-applied: + +```sql +-- View recent migrations +SELECT migration_name, finished_at, rolled_back_at, logs +FROM "_prisma_migrations" +ORDER BY started_at DESC +LIMIT 10; + +-- Delete the failed migration entry +DELETE FROM "_prisma_migrations" +WHERE migration_name = ''; +``` + +After deleting the entry, restart LiteLLM — it will re-apply the migration on startup. + +#### Step 2 — If that doesn't work, use `prisma db push` + +If deleting the migration entry and restarting doesn't resolve the issue, sync the schema directly: + +```bash +DATABASE_URL="" prisma db push +``` + +This bypasses migration history and forces the database schema to match the Prisma schema. + +--- + +### 2. `New migrations cannot be applied before the error is recovered from` + +**Cause:** A previous migration failed (recorded with an error in `_prisma_migrations`), and Prisma refuses to apply any new migrations until the failure is resolved. + +**How to fix:** + +1. Find the failed migration: + +```sql +SELECT migration_name, finished_at, rolled_back_at, logs +FROM "_prisma_migrations" +WHERE finished_at IS NULL OR rolled_back_at IS NOT NULL +ORDER BY started_at DESC; +``` + +2. Delete the failed entry and restart LiteLLM: + +```sql +DELETE FROM "_prisma_migrations" +WHERE migration_name = ''; +``` + +3. If that doesn't work, use `prisma db push`: + +```bash +DATABASE_URL="" prisma db push +``` + +--- + +### 3. Migration state mismatch after version rollback + +**Cause:** You upgraded to version X (new migrations applied), rolled back to version Y, then upgraded again. The `_prisma_migrations` table has stale entries for migrations that were partially applied or correspond to a schema state that no longer exists. + +**Fix:** + +1. Inspect the migration table for problematic entries: + +```sql +SELECT migration_name, started_at, finished_at, rolled_back_at, logs +FROM "_prisma_migrations" +ORDER BY started_at DESC +LIMIT 20; +``` + +2. For each migration that shouldn't be there (i.e., from the version you rolled back from), delete the entry: + ```sql + DELETE FROM "_prisma_migrations" WHERE migration_name = ''; + ``` + +3. Restart LiteLLM to re-run migrations. + +4. If that doesn't work, use `prisma db push`: + +```bash +DATABASE_URL="" prisma db push +``` diff --git a/docs/my-website/docs/tutorials/claude_code_beta_headers.md b/docs/my-website/docs/tutorials/claude_code_beta_headers.md new file mode 100644 index 00000000000..9c1645e0277 --- /dev/null +++ b/docs/my-website/docs/tutorials/claude_code_beta_headers.md @@ -0,0 +1,129 @@ +import Image from '@theme/IdealImage'; + +# Claude Code - Fixing Invalid Beta Header Errors + +When using Claude Code with LiteLLM and non-Anthropic providers (Bedrock, Azure AI, Vertex AI), you may encounter "invalid beta header" errors. This guide explains how to fix these errors locally or contribute a fix to LiteLLM. + +## What Are Beta Headers? + +Anthropic uses beta headers to enable experimental features in Claude. When you use Claude Code, it may send beta headers like: + +``` +anthropic-beta: prompt-caching-scope-2026-01-05,advanced-tool-use-2025-11-20 +``` + +However, not all providers support all Anthropic beta features. When an unsupported beta header is sent to a provider, you'll see an error. + +## Common Error Message + +```bash +Error: The model returned the following errors: invalid beta flag +``` + +## How LiteLLM Handles Beta Headers + +LiteLLM automatically filters out unsupported beta headers using a configuration file: + +``` +litellm/litellm/anthropic_beta_headers_config.json +``` + +This JSON file lists which beta headers are **unsupported** for each provider. Headers not in the unsupported list are passed through to the provider. + +## Quick Fix: Update Config Locally + +If you encounter an invalid beta header error, you can fix it immediately by updating the config file locally. + +### Step 1: Locate the Config File + +Find the file in your LiteLLM installation: + +```bash +# If installed via pip +cd $(python -c "import litellm; import os; print(os.path.dirname(litellm.__file__))") + +# The config file is at: +# litellm/anthropic_beta_headers_config.json +``` + +### Step 2: Add the Unsupported Header + +Open `anthropic_beta_headers_config.json` and add the problematic header to the appropriate provider's list: + +```json title="anthropic_beta_headers_config.json" +{ + "description": "Unsupported Anthropic beta headers for each provider. Headers listed here will be dropped. Headers not listed are passed through as-is.", + "anthropic": [], + "azure_ai": [], + "bedrock_converse": [ + "prompt-caching-scope-2026-01-05", + "bash_20250124", + "bash_20241022", + "text_editor_20250124", + "text_editor_20241022", + "compact-2026-01-12", + "advanced-tool-use-2025-11-20", + "web-fetch-2025-09-10", + "code-execution-2025-08-25", + "skills-2025-10-02", + "files-api-2025-04-14" + ], + "bedrock": [ + "advanced-tool-use-2025-11-20", + "prompt-caching-scope-2026-01-05", + "structured-outputs-2025-11-13", + "web-fetch-2025-09-10", + "code-execution-2025-08-25", + "skills-2025-10-02", + "files-api-2025-04-14" + ], + "vertex_ai": [ + "prompt-caching-scope-2026-01-05" + ] +} +``` + +### Step 3: Restart Your Application + +After updating the config file, restart your LiteLLM proxy or application: + +```bash +# If using LiteLLM proxy +litellm --config config.yaml + +# If using Python SDK +# Just restart your Python application +``` + +The updated configuration will be loaded automatically. + +## Contributing a Fix to LiteLLM + +Help the community by contributing your fix! If your local changes work, please raise a PR with the addition of the header and we will merge it. + + +## How Beta Header Filtering Works + +When you make a request through LiteLLM: + +```mermaid +sequenceDiagram + participant CC as Claude Code + participant LP as LiteLLM + participant Config as Beta Headers Config + participant Provider as Provider (Bedrock/Azure/etc) + + CC->>LP: Request with beta headers + Note over CC,LP: anthropic-beta: header1,header2,header3 + + LP->>Config: Load unsupported headers for provider + Config-->>LP: Returns unsupported list + + Note over LP: Filter headers:
- Remove unsupported
- Keep supported + + LP->>Provider: Request with filtered headers + Note over LP,Provider: anthropic-beta: header2
(header1, header3 removed) + + Provider-->>LP: Success response + LP-->>CC: Response +``` \ No newline at end of file diff --git a/docs/my-website/docs/tutorials/copilotkit_sdk.md b/docs/my-website/docs/tutorials/copilotkit_sdk.md new file mode 100644 index 00000000000..fc4db8bfe3e --- /dev/null +++ b/docs/my-website/docs/tutorials/copilotkit_sdk.md @@ -0,0 +1,99 @@ +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# CopilotKit SDK with LiteLLM + +Use CopilotKit SDK with any LLM provider through LiteLLM Proxy. + +> **Note:** CopilotKit SDK integration with LiteLLM Proxy works with LiteLLM v1.81.7-nightly or higher. + + +## Quick Start + +### 1. Add Model to Config + +```yaml title="config.yaml" +model_list: + - model_name: claude-sonnet-4-5 + litellm_params: + model: "anthropic/claude-sonnet-4-5-20250514-v1:0" + api_key: "os.environ/ANTHROPIC_API_KEY" +``` + +### 2. Start LiteLLM Proxy + +```bash +litellm --config config.yaml +``` + +### 3. Use CopilotKit SDK + +```typescript +import OpenAI from "openai"; +import { + CopilotRuntime, + OpenAIAdapter, + copilotRuntimeNextJSAppRouterEndpoint, +} from "@copilotkit/runtime"; +import { NextRequest } from "next/server"; + +const model = "claude-sonnet-4-5"; + +const openai = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY || "sk-12345", + baseURL: process.env.OPENAI_BASE_URL || "http://localhost:4000/v1", +}); + +const serviceAdapter = new OpenAIAdapter({ openai, model }); +const runtime = new CopilotRuntime(); + +export const POST = async (req: NextRequest) => { + const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({ + runtime, + serviceAdapter, + endpoint: "/api/copilotkit", + }); + return handleRequest(req); +}; +``` + +### 4. Test + +```bash +curl -X POST http://localhost:3000/api/copilotkit \ + -H "Content-Type: application/json" \ + -d '{ + "method": "agent/run", + "params": { + "agentId": "default" + }, + "runId": "your_run_id", + "threadId": "your_thread_id", + "runId": ""your_run_id"", + "tools": [], + "context": [], + "forwardedProps": {}, + "state": {}, + "messages": [ + { + "id": "166e573e-f7c6-4c0f-8685-04dbefec18be", + "content": "Hi", + "role": "user" + } + ] + } +}' +``` + +## Environment Variables + +| Variable | Value | Description | +|----------|-------|-------------| +| `OPENAI_API_KEY` | `sk-12345` | Your LiteLLM API key | +| `OPENAI_BASE_URL` | `http://localhost:4000/v1` | LiteLLM proxy URL | + + +## Related Resources + +- [CopilotKit Documentation](https://docs.copilotkit.ai) +- [LiteLLM Proxy Quick Start](../proxy/quick_start) diff --git a/docs/my-website/docs/tutorials/livekit_xai_realtime.md b/docs/my-website/docs/tutorials/livekit_xai_realtime.md new file mode 100644 index 00000000000..1d70186382f --- /dev/null +++ b/docs/my-website/docs/tutorials/livekit_xai_realtime.md @@ -0,0 +1,190 @@ +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# LiveKit xAI Realtime Voice Agent + +Use LiveKit's xAI Grok Voice Agent plugin with LiteLLM Proxy to build low-latency voice AI agents. + +The LiveKit Agents framework provides tools for building real-time voice and video AI applications. By routing through LiteLLM Proxy, you get unified access to multiple realtime voice providers, cost tracking, rate limiting, and more. + +## Quick Start + +### 1. Install Dependencies + +```bash +pip install livekit-agents[xai] +``` + +### 2. Start LiteLLM Proxy + +Create a config file with your xAI realtime model: + +```yaml title="config.yaml" showLineNumbers +model_list: + - model_name: grok-voice-agent + litellm_params: + model: xai/grok-2-vision-1212 + api_key: os.environ/XAI_API_KEY + model_info: + mode: realtime + +litellm_settings: + drop_params: True + +general_settings: + master_key: sk-1234 # Change this to a secure key +``` + +Start the proxy: + +```bash +litellm --config config.yaml --port 4000 +``` + +### 3. Configure LiveKit xAI Plugin + +Point LiveKit's xAI plugin to your LiteLLM proxy: + +```python +from livekit.plugins import xai + +# Configure xAI to use LiteLLM proxy +model = xai.realtime.RealtimeModel( + voice="ara", # Voice option + api_key="sk-1234", # Your LiteLLM proxy master key + base_url="http://localhost:4000", # LiteLLM proxy URL +) +``` + +## Complete Example + +Here's a complete working example: + + + + +```python +#!/usr/bin/env python3 +""" +Simple xAI realtime voice agent through LiteLLM proxy. +""" +import asyncio +import json +import websockets + +PROXY_URL = "ws://localhost:4000/v1/realtime" +API_KEY = "sk-1234" +MODEL = "grok-voice-agent" + +async def run_voice_agent(): + """Connect to xAI realtime API through LiteLLM proxy""" + url = f"{PROXY_URL}?model={MODEL}" + headers = {"Authorization": f"Bearer {API_KEY}"} + + async with websockets.connect(url, extra_headers=headers) as ws: + # Wait for initial connection event + initial = json.loads(await ws.recv()) + print(f"✅ Connected: {initial['type']}") + + # Send user message + await ws.send(json.dumps({ + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [{ + "type": "input_text", + "text": "Hello! Tell me a joke." + }] + } + })) + + # Request response + await ws.send(json.dumps({ + "type": "response.create", + "response": {"modalities": ["text", "audio"]} + })) + + # Collect response + transcript = [] + async for message in ws: + event = json.loads(message) + + # Capture text response + if event['type'] == 'response.output_audio_transcript.delta': + transcript.append(event['delta']) + print(event['delta'], end='', flush=True) + + # Done when response completes + elif event['type'] == 'response.done': + break + + print(f"\n\n✅ Full response: {''.join(transcript)}") + +if __name__ == "__main__": + asyncio.run(run_voice_agent()) +``` + + + + + +```python +from livekit.agents import Agent, AgentSession, WorkerOptions, cli +from livekit.plugins import xai + +class VoiceAgent(Agent): + def __init__(self): + super().__init__( + instructions="You are a helpful voice assistant.", + llm=xai.realtime.RealtimeModel( + voice="ara", + api_key="sk-1234", + base_url="http://localhost:4000", + ), + ) + +if __name__ == "__main__": + cli.run_app( + WorkerOptions( + agent_factory=VoiceAgent, + ) + ) +``` + + + + +## Running the Example + +1. **Start LiteLLM Proxy** (if not already running): + ```bash + litellm --config config.yaml --port 4000 + ``` + +2. **Run the example**: + ```bash + python your_script.py + ``` + +## Expected Output + +``` +✅ Connected: conversation.created +Hello! Here's a joke for you: Why don't scientists trust atoms? +Because they make up everything! + +✅ Full response: Hello! Here's a joke for you: Why don't scientists trust atoms? Because they make up everything! +``` + + +## Complete Working Example + +**[LiveKit Agent SDK Cookbook](https://github.com/BerriAI/litellm/tree/main/cookbook/livekit_agent_sdk)** + + +## Learn More + +- [xAI Realtime API](/docs/providers/xai_realtime) +- [LiveKit xAI Plugin](https://docs.livekit.io/agents/models/realtime/plugins/xai/) +- [LiteLLM Realtime API](/docs/realtime) diff --git a/docs/my-website/img/okta_access_policies.png b/docs/my-website/img/okta_access_policies.png new file mode 100644 index 00000000000..e09adc2ce7f Binary files /dev/null and b/docs/my-website/img/okta_access_policies.png differ diff --git a/docs/my-website/img/okta_authorization_server.png b/docs/my-website/img/okta_authorization_server.png new file mode 100644 index 00000000000..bddb3e07a4a Binary files /dev/null and b/docs/my-website/img/okta_authorization_server.png differ diff --git a/docs/my-website/img/okta_client_credentials.png b/docs/my-website/img/okta_client_credentials.png new file mode 100644 index 00000000000..a00a9f4657e Binary files /dev/null and b/docs/my-website/img/okta_client_credentials.png differ diff --git a/docs/my-website/img/okta_redirect_uri.png b/docs/my-website/img/okta_redirect_uri.png new file mode 100644 index 00000000000..a1e58560c72 Binary files /dev/null and b/docs/my-website/img/okta_redirect_uri.png differ diff --git a/docs/my-website/img/okta_security_api.png b/docs/my-website/img/okta_security_api.png new file mode 100644 index 00000000000..7f9e218074c Binary files /dev/null and b/docs/my-website/img/okta_security_api.png differ diff --git a/docs/my-website/img/ui_tools.png b/docs/my-website/img/ui_tools.png new file mode 100644 index 00000000000..6f4d0f87410 Binary files /dev/null and b/docs/my-website/img/ui_tools.png differ diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js index 95a44128377..545d46f7f37 100644 --- a/docs/my-website/sidebars.js +++ b/docs/my-website/sidebars.js @@ -79,6 +79,7 @@ const sidebars = { "proxy/guardrails/panw_prisma_airs", "proxy/guardrails/secret_detection", "proxy/guardrails/custom_guardrail", + "proxy/guardrails/custom_code_guardrail", "proxy/guardrails/prompt_injection", "proxy/guardrails/tool_permission", "proxy/guardrails/zscaler_ai_guard", @@ -128,6 +129,7 @@ const sidebars = { "tutorials/claude_mcp", "tutorials/claude_non_anthropic_models", "tutorials/claude_code_plugin_marketplace", + "tutorials/claude_code_beta_headers", ] }, "tutorials/opencode_integration", @@ -150,7 +152,9 @@ const sidebars = { }, items: [ "tutorials/claude_agent_sdk", + "tutorials/copilotkit_sdk", "tutorials/google_adk", + "tutorials/livekit_xai_realtime", ] }, @@ -442,6 +446,7 @@ const sidebars = { label: "Spend Tracking", items: [ "proxy/cost_tracking", + "proxy/request_tags", "proxy/custom_pricing", "proxy/pricing_calculator", "proxy/provider_margins", @@ -468,6 +473,7 @@ const sidebars = { label: "/a2a - A2A Agent Gateway", items: [ "a2a", + "a2a_invoking_agents", "a2a_cost_tracking", "a2a_agent_permissions" ], @@ -537,6 +543,8 @@ const sidebars = { items: [ "mcp", "mcp_usage", + "mcp_public_internet", + "mcp_semantic_filter", "mcp_control", "mcp_cost", "mcp_guardrail", @@ -715,6 +723,7 @@ const sidebars = { "providers/bedrock_agents", "providers/bedrock_writer", "providers/bedrock_batches", + "providers/bedrock_realtime_with_audio", "providers/aws_polly", "providers/bedrock_vector_store", ] @@ -847,7 +856,14 @@ const sidebars = { "providers/watsonx/audio_transcription", ] }, - "providers/xai", + { + type: "category", + label: "xAI", + items: [ + "providers/xai", + "providers/xai_realtime", + ] + }, "providers/xiaomi_mimo", "providers/xinference", "providers/zai", @@ -1041,6 +1057,7 @@ const sidebars = { type: "category", label: "Issue Reporting", items: [ + "troubleshoot/prisma_migrations", "troubleshoot/cpu_issues", "troubleshoot/memory_issues", "troubleshoot/spend_queue_warnings", diff --git a/enterprise/dist/litellm_enterprise-0.1.29-py3-none-any.whl b/enterprise/dist/litellm_enterprise-0.1.29-py3-none-any.whl new file mode 100644 index 00000000000..0895ecbc427 Binary files /dev/null and b/enterprise/dist/litellm_enterprise-0.1.29-py3-none-any.whl differ diff --git a/enterprise/dist/litellm_enterprise-0.1.29.tar.gz b/enterprise/dist/litellm_enterprise-0.1.29.tar.gz new file mode 100644 index 00000000000..6781cf26cc9 Binary files /dev/null and b/enterprise/dist/litellm_enterprise-0.1.29.tar.gz differ diff --git a/enterprise/dist/litellm_enterprise-0.1.30-py3-none-any.whl b/enterprise/dist/litellm_enterprise-0.1.30-py3-none-any.whl new file mode 100644 index 00000000000..0165bb096c0 Binary files /dev/null and b/enterprise/dist/litellm_enterprise-0.1.30-py3-none-any.whl differ diff --git a/enterprise/dist/litellm_enterprise-0.1.30.tar.gz b/enterprise/dist/litellm_enterprise-0.1.30.tar.gz new file mode 100644 index 00000000000..2bb7510e5d3 Binary files /dev/null and b/enterprise/dist/litellm_enterprise-0.1.30.tar.gz differ diff --git a/enterprise/dist/litellm_enterprise-0.1.31-py3-none-any.whl b/enterprise/dist/litellm_enterprise-0.1.31-py3-none-any.whl new file mode 100644 index 00000000000..03cadbd9023 Binary files /dev/null and b/enterprise/dist/litellm_enterprise-0.1.31-py3-none-any.whl differ diff --git a/enterprise/dist/litellm_enterprise-0.1.31.tar.gz b/enterprise/dist/litellm_enterprise-0.1.31.tar.gz new file mode 100644 index 00000000000..1ba1a717f62 Binary files /dev/null and b/enterprise/dist/litellm_enterprise-0.1.31.tar.gz differ diff --git a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py index 61e0745bab1..d3e04769300 100644 --- a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py +++ b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py @@ -30,8 +30,15 @@ from litellm.integrations.email_templates.templates import ( MAX_BUDGET_ALERT_EMAIL_TEMPLATE, SOFT_BUDGET_ALERT_EMAIL_TEMPLATE, + TEAM_SOFT_BUDGET_ALERT_EMAIL_TEMPLATE, +) +from litellm.proxy._types import ( + CallInfo, + InvitationNew, + Litellm_EntityType, + UserAPIKeyAuth, + WebhookEvent, ) -from litellm.proxy._types import CallInfo, InvitationNew, UserAPIKeyAuth, WebhookEvent from litellm.secret_managers.main import get_secret_bool from litellm.types.integrations.slack_alerting import LITELLM_LOGO_URL from litellm.constants import ( @@ -217,6 +224,78 @@ async def send_soft_budget_alert_email(self, event: WebhookEvent): ) pass + async def send_team_soft_budget_alert_email(self, event: WebhookEvent): + """ + Send email to team members when team soft budget is crossed + Supports multiple recipients via alert_emails field from team metadata + """ + # Collect all recipient emails + recipient_emails: List[str] = [] + + # Add additional alert emails from team metadata.soft_budget_alert_emails + if hasattr(event, "alert_emails") and event.alert_emails: + for email in event.alert_emails: + if email and email not in recipient_emails: # Avoid duplicates + recipient_emails.append(email) + + # If no recipients found, skip sending + if not recipient_emails: + verbose_proxy_logger.warning( + f"No recipient emails found for team soft budget alert. event={event.model_dump(exclude_none=True)}" + ) + return + + # Validate that we have at least one valid email address + first_recipient_email = recipient_emails[0] + if not first_recipient_email or not first_recipient_email.strip(): + verbose_proxy_logger.warning( + f"Invalid recipient email found for team soft budget alert. event={event.model_dump(exclude_none=True)}" + ) + return + + verbose_proxy_logger.debug( + f"send_team_soft_budget_alert_email_event: {json.dumps(event.model_dump(exclude_none=True), indent=4, default=str)}" + ) + + # Get email params using the first recipient email (for template formatting) + # For team alerts with alert_emails, we don't need user_id lookup since we already have email addresses + # Pass user_id=None to prevent _get_email_params from trying to look up email from a potentially None user_id + email_params = await self._get_email_params( + email_event=EmailEvent.soft_budget_crossed, + user_id=None, # Team alerts don't require user_id when alert_emails are provided + user_email=first_recipient_email, + event_message=event.event_message, + ) + + # Format budget values + soft_budget_str = f"${event.soft_budget}" if event.soft_budget is not None else "N/A" + spend_str = f"${event.spend}" if event.spend is not None else "$0.00" + max_budget_info = "" + if event.max_budget is not None: + max_budget_info = f"Maximum Budget: ${event.max_budget}
" + + # Use team alias or generic greeting + team_alias = event.team_alias or "Team" + + email_html_content = TEAM_SOFT_BUDGET_ALERT_EMAIL_TEMPLATE.format( + email_logo_url=email_params.logo_url, + team_alias=team_alias, + soft_budget=soft_budget_str, + spend=spend_str, + max_budget_info=max_budget_info, + base_url=email_params.base_url, + email_support_contact=email_params.support_contact, + ) + + # Send email to all recipients + await self.send_email( + from_email=self.DEFAULT_LITELLM_EMAIL, + to_email=recipient_emails, + subject=email_params.subject, + html_body=email_html_content, + ) + pass + async def send_max_budget_alert_email(self, event: WebhookEvent): """ Send email to user when max budget alert threshold is reached @@ -285,15 +364,36 @@ async def budget_alerts( # - Don't re-alert, if alert already sent _cache: DualCache = self.internal_usage_cache - # percent of max_budget left to spend - if user_info.max_budget is None and user_info.soft_budget is None: - return - # For soft_budget alerts, check if we've already sent an alert if type == "soft_budget": + # For team soft budget alerts, we only need team soft_budget to be set + # For other entity types, we need either max_budget or soft_budget + if user_info.event_group == Litellm_EntityType.TEAM: + if user_info.soft_budget is None: + return + # For team soft budget alerts, require alert_emails to be configured + # Team soft budget alerts are sent via metadata.soft_budget_alerting_emails + if user_info.alert_emails is None or len(user_info.alert_emails) == 0: + verbose_proxy_logger.debug( + "Skipping team soft budget email alert: no alert_emails configured", + ) + return + else: + # For non-team alerts, require either max_budget or soft_budget + if user_info.max_budget is None and user_info.soft_budget is None: + return if user_info.soft_budget is not None and user_info.spend >= user_info.soft_budget: # Generate cache key based on event type and identifier - _id = user_info.token or user_info.user_id or "default_id" + # Use appropriate ID based on event_group to ensure unique cache keys per entity type + if user_info.event_group == Litellm_EntityType.TEAM: + _id = user_info.team_id or "default_id" + elif user_info.event_group == Litellm_EntityType.ORGANIZATION: + _id = user_info.organization_id or "default_id" + elif user_info.event_group == Litellm_EntityType.USER: + _id = user_info.user_id or "default_id" + else: + # For KEY and other types, use token or user_id + _id = user_info.token or user_info.user_id or "default_id" _cache_key = f"email_budget_alerts:soft_budget_crossed:{_id}" # Check if we've already sent this alert @@ -318,10 +418,15 @@ async def budget_alerts( projected_exceeded_date=user_info.projected_exceeded_date, projected_spend=user_info.projected_spend, event_group=user_info.event_group, + alert_emails=user_info.alert_emails, ) try: - await self.send_soft_budget_alert_email(webhook_event) + # Use team-specific function for team alerts, otherwise use standard function + if user_info.event_group == Litellm_EntityType.TEAM: + await self.send_team_soft_budget_alert_email(webhook_event) + else: + await self.send_soft_budget_alert_email(webhook_event) # Cache the alert to prevent duplicate sends await _cache.async_set_cache( diff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py index d4ee4042b1a..bb25e4f0626 100644 --- a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py +++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py @@ -53,7 +53,7 @@ async def check_batch_cost(self): jobs = await self.prisma_client.db.litellm_managedobjecttable.find_many( where={ - "status": "validating", + "status": {"in": ["validating", "in_progress", "finalizing"]}, "file_purpose": "batch", } ) diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py index 5ee3372cca7..569ea17f6d8 100644 --- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py +++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py @@ -166,7 +166,11 @@ async def store_unified_object_id( "updated_by": user_api_key_dict.user_id, "status": file_object.status, }, - "update": {}, # don't do anything if it already exists + "update": { + "file_object": file_object.model_dump_json(), + "status": file_object.status, + "updated_by": user_api_key_dict.user_id, + }, # FIX: Update status and file_object on every operation to keep state in sync }, ) @@ -354,6 +358,31 @@ async def check_managed_file_id_access( ) return False + async def check_file_ids_access( + self, file_ids: List[str], user_api_key_dict: UserAPIKeyAuth + ) -> None: + """ + Check if the user has access to a list of file IDs. + Only checks managed (unified) file IDs. + + Args: + file_ids: List of file IDs to check access for + user_api_key_dict: User API key authentication details + + Raises: + HTTPException: If user doesn't have access to any of the files + """ + for file_id in file_ids: + is_unified_file_id = _is_base64_encoded_unified_file_id(file_id) + if is_unified_file_id: + if not await self.can_user_call_unified_file_id( + file_id, user_api_key_dict + ): + raise HTTPException( + status_code=403, + detail=f"User {user_api_key_dict.user_id} does not have access to the file {file_id}", + ) + async def async_pre_call_hook( # noqa: PLR0915 self, user_api_key_dict: UserAPIKeyAuth, @@ -387,6 +416,9 @@ async def async_pre_call_hook( # noqa: PLR0915 if messages: file_ids = self.get_file_ids_from_messages(messages) if file_ids: + # Check user has access to all managed files + await self.check_file_ids_access(file_ids, user_api_key_dict) + # Check if any files are stored in storage backends and need base64 conversion # This is needed for Vertex AI/Gemini which requires base64 content is_vertex_ai = model and ("vertex_ai" in model or "gemini" in model.lower()) @@ -402,15 +434,27 @@ async def async_pre_call_hook( # noqa: PLR0915 ) data["model_file_id_mapping"] = model_file_id_mapping elif call_type == CallTypes.aresponses.value or call_type == CallTypes.responses.value: - # Handle managed files in responses API input + # Handle managed files in responses API input and tools + file_ids = [] + + # Extract file IDs from input parameter input_data = data.get("input") if input_data: - file_ids = self.get_file_ids_from_responses_input(input_data) - if file_ids: - model_file_id_mapping = await self.get_model_file_id_mapping( - file_ids, user_api_key_dict.parent_otel_span - ) - data["model_file_id_mapping"] = model_file_id_mapping + file_ids.extend(self.get_file_ids_from_responses_input(input_data)) + + # Extract file IDs from tools parameter (e.g., code_interpreter container) + tools = data.get("tools") + if tools: + file_ids.extend(self.get_file_ids_from_responses_tools(tools)) + + if file_ids: + # Check user has access to all managed files + await self.check_file_ids_access(file_ids, user_api_key_dict) + + model_file_id_mapping = await self.get_model_file_id_mapping( + file_ids, user_api_key_dict.parent_otel_span + ) + data["model_file_id_mapping"] = model_file_id_mapping elif call_type == CallTypes.afile_content.value: retrieve_file_id = cast(Optional[str], data.get("file_id")) potential_file_id = ( @@ -460,8 +504,6 @@ async def async_pre_call_hook( # noqa: PLR0915 if retrieve_object_id else False ) - print(f"🔥potential_llm_object_id: {potential_llm_object_id}") - print(f"🔥retrieve_object_id: {retrieve_object_id}") if potential_llm_object_id and retrieve_object_id: ## VALIDATE USER HAS ACCESS TO THE OBJECT ## if not await self.can_user_call_unified_object_id( @@ -614,6 +656,41 @@ def get_file_ids_from_responses_input( return file_ids + def get_file_ids_from_responses_tools( + self, tools: List[Dict[str, Any]] + ) -> List[str]: + """ + Gets file ids from responses API tools parameter. + + The tools can contain code_interpreter with container.file_ids: + [ + { + "type": "code_interpreter", + "container": {"type": "auto", "file_ids": ["file-123", "file-456"]} + } + ] + """ + file_ids: List[str] = [] + + if not isinstance(tools, list): + return file_ids + + for tool in tools: + if not isinstance(tool, dict): + continue + + # Check for code_interpreter with container file_ids + if tool.get("type") == "code_interpreter": + container = tool.get("container") + if isinstance(container, dict): + container_file_ids = container.get("file_ids") + if isinstance(container_file_ids, list): + for file_id in container_file_ids: + if isinstance(file_id, str): + file_ids.append(file_id) + + return file_ids + async def get_model_file_id_mapping( self, file_ids: List[str], litellm_parent_otel_span: Span ) -> dict: diff --git a/enterprise/pyproject.toml b/enterprise/pyproject.toml index 0d86460a649..eca5cdb97df 100644 --- a/enterprise/pyproject.toml +++ b/enterprise/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "litellm-enterprise" -version = "0.1.28" +version = "0.1.31" description = "Package for LiteLLM Enterprise features" authors = ["BerriAI"] readme = "README.md" @@ -22,7 +22,7 @@ requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" [tool.commitizen] -version = "0.1.28" +version = "0.1.31" version_files = [ "pyproject.toml:version", "../requirements.txt:litellm-enterprise==", diff --git a/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.30-py3-none-any.whl b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.30-py3-none-any.whl new file mode 100644 index 00000000000..383f9b7b43f Binary files /dev/null and b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.30-py3-none-any.whl differ diff --git a/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.30.tar.gz b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.30.tar.gz new file mode 100644 index 00000000000..484c28ba7b1 Binary files /dev/null and b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.30.tar.gz differ diff --git a/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.31-py3-none-any.whl b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.31-py3-none-any.whl new file mode 100644 index 00000000000..90b36bd78ac Binary files /dev/null and b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.31-py3-none-any.whl differ diff --git a/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.31.tar.gz b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.31.tar.gz new file mode 100644 index 00000000000..64607235479 Binary files /dev/null and b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.31.tar.gz differ diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205091235_allow_team_guardrail_config/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205091235_allow_team_guardrail_config/migration.sql new file mode 100644 index 00000000000..000b96b3b87 --- /dev/null +++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205091235_allow_team_guardrail_config/migration.sql @@ -0,0 +1,6 @@ +-- AlterTable +ALTER TABLE "LiteLLM_DeletedTeamTable" ADD COLUMN "allow_team_guardrail_config" BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable +ALTER TABLE "LiteLLM_TeamTable" ADD COLUMN "allow_team_guardrail_config" BOOLEAN NOT NULL DEFAULT false; + diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205144610_add_soft_budget_to_team_table/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205144610_add_soft_budget_to_team_table/migration.sql new file mode 100644 index 00000000000..a64f1de342f --- /dev/null +++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260205144610_add_soft_budget_to_team_table/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE "LiteLLM_TeamTable" ADD COLUMN "soft_budget" DOUBLE PRECISION; + diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma index b118400b620..c2d2299fb25 100644 --- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma +++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma @@ -113,6 +113,7 @@ model LiteLLM_TeamTable { members_with_roles Json @default("{}") metadata Json @default("{}") max_budget Float? + soft_budget Float? spend Float @default(0.0) models String[] max_parallel_requests Int? @@ -129,6 +130,7 @@ model LiteLLM_TeamTable { team_member_permissions String[] @default([]) policies String[] @default([]) model_id Int? @unique // id for LiteLLM_ModelTable -> stores team-level model aliases + allow_team_guardrail_config Boolean @default(false) // if true, team admin can configure guardrails for this team litellm_organization_table LiteLLM_OrganizationTable? @relation(fields: [organization_id], references: [organization_id]) litellm_model_table LiteLLM_ModelTable? @relation(fields: [model_id], references: [id]) object_permission LiteLLM_ObjectPermissionTable? @relation(fields: [object_permission_id], references: [object_permission_id]) @@ -160,7 +162,8 @@ model LiteLLM_DeletedTeamTable { team_member_permissions String[] @default([]) policies String[] @default([]) model_id Int? // id for LiteLLM_ModelTable -> stores team-level model aliases - + allow_team_guardrail_config Boolean @default(false) + // Original timestamps from team creation/updates created_at DateTime? @map("created_at") updated_at DateTime? @map("updated_at") @@ -260,6 +263,7 @@ model LiteLLM_MCPServerTable { token_url String? registration_url String? allow_all_keys Boolean @default(false) + available_on_public_internet Boolean @default(false) } // Generate Tokens for Proxy @@ -774,6 +778,7 @@ model LiteLLM_GuardrailsTable { guardrail_name String @unique litellm_params Json guardrail_info Json? + team_id String? created_at DateTime @default(now()) updated_at DateTime @updatedAt } diff --git a/litellm-proxy-extras/pyproject.toml b/litellm-proxy-extras/pyproject.toml index fb6996b71db..0e72cd90813 100644 --- a/litellm-proxy-extras/pyproject.toml +++ b/litellm-proxy-extras/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "litellm-proxy-extras" -version = "0.4.29" +version = "0.4.31" description = "Additional files for the LiteLLM Proxy. Reduces the size of the main litellm package." authors = ["BerriAI"] readme = "README.md" @@ -22,7 +22,7 @@ requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" [tool.commitizen] -version = "0.4.29" +version = "0.4.31" version_files = [ "pyproject.toml:version", "../requirements.txt:litellm-proxy-extras==", diff --git a/litellm/__init__.py b/litellm/__init__.py index a74a79635f0..8174b9d2655 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -261,6 +261,8 @@ in_memory_llm_clients_cache: "LLMClientCache" safe_memory_mode: bool = False enable_azure_ad_token_refresh: Optional[bool] = False +# Proxy Authentication - auto-obtain/refresh OAuth2/JWT tokens for LiteLLM Proxy +proxy_auth: Optional[Any] = None ### DEFAULT AZURE API VERSION ### AZURE_DEFAULT_API_VERSION = "2025-02-01-preview" # this is updated to the latest ### DEFAULT WATSONX API VERSION ### @@ -351,7 +353,7 @@ max_user_budget: Optional[float] = None default_max_internal_user_budget: Optional[float] = None max_internal_user_budget: Optional[float] = None -max_ui_session_budget: Optional[float] = 10 # $10 USD budgets for UI Chat sessions +max_ui_session_budget: Optional[float] = 0.25 # $0.25 USD budgets for UI Chat sessions internal_user_budget_duration: Optional[str] = None tag_budget_config: Optional[Dict[str, "BudgetConfig"]] = None max_end_user_budget: Optional[float] = None @@ -1378,6 +1380,7 @@ def set_global_gitlab_config(config: Dict[str, Any]) -> None: from .llms.topaz.image_variations.transformation import TopazImageVariationConfig as TopazImageVariationConfig from litellm.llms.openai.completion.transformation import OpenAITextCompletionConfig as OpenAITextCompletionConfig from .llms.groq.chat.transformation import GroqChatConfig as GroqChatConfig + from .llms.a2a.chat.transformation import A2AConfig as A2AConfig from .llms.voyage.embedding.transformation import VoyageEmbeddingConfig as VoyageEmbeddingConfig from .llms.voyage.embedding.transformation_contextual import VoyageContextualEmbeddingConfig as VoyageContextualEmbeddingConfig from .llms.infinity.embedding.transformation import InfinityEmbeddingConfig as InfinityEmbeddingConfig diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.py index 0e52e9a59eb..a01fe9c11db 100644 --- a/litellm/_lazy_imports_registry.py +++ b/litellm/_lazy_imports_registry.py @@ -213,6 +213,7 @@ "TopazImageVariationConfig", "OpenAITextCompletionConfig", "GroqChatConfig", + "A2AConfig", "GenAIHubOrchestrationConfig", "VoyageEmbeddingConfig", "VoyageContextualEmbeddingConfig", @@ -850,6 +851,7 @@ "OpenAITextCompletionConfig", ), "GroqChatConfig": (".llms.groq.chat.transformation", "GroqChatConfig"), + "A2AConfig": (".llms.a2a.chat.transformation", "A2AConfig"), "GenAIHubOrchestrationConfig": ( ".llms.sap.chat.transformation", "GenAIHubOrchestrationConfig", diff --git a/litellm/a2a_protocol/__init__.py b/litellm/a2a_protocol/__init__.py index d8d349bb98a..85c03687e25 100644 --- a/litellm/a2a_protocol/__init__.py +++ b/litellm/a2a_protocol/__init__.py @@ -39,6 +39,12 @@ """ from litellm.a2a_protocol.client import A2AClient +from litellm.a2a_protocol.exceptions import ( + A2AAgentCardError, + A2AConnectionError, + A2AError, + A2ALocalhostURLError, +) from litellm.a2a_protocol.main import ( aget_agent_card, asend_message, @@ -49,11 +55,19 @@ from litellm.types.agents import LiteLLMSendMessageResponse __all__ = [ + # Client "A2AClient", + # Functions "asend_message", "send_message", "asend_message_streaming", "aget_agent_card", "create_a2a_client", + # Response types "LiteLLMSendMessageResponse", + # Exceptions + "A2AError", + "A2AConnectionError", + "A2AAgentCardError", + "A2ALocalhostURLError", ] diff --git a/litellm/a2a_protocol/card_resolver.py b/litellm/a2a_protocol/card_resolver.py index 7c4c5af149d..4c5dd3e3ba6 100644 --- a/litellm/a2a_protocol/card_resolver.py +++ b/litellm/a2a_protocol/card_resolver.py @@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional from litellm._logging import verbose_logger +from litellm.constants import LOCALHOST_URL_PATTERNS if TYPE_CHECKING: from a2a.types import AgentCard @@ -26,15 +27,61 @@ pass +def is_localhost_or_internal_url(url: Optional[str]) -> bool: + """ + Check if a URL is a localhost or internal URL. + + This detects common development URLs that are accidentally left in + agent cards when deploying to production. + + Args: + url: The URL to check + + Returns: + True if the URL is localhost/internal + """ + if not url: + return False + + url_lower = url.lower() + + return any(pattern in url_lower for pattern in LOCALHOST_URL_PATTERNS) + + +def fix_agent_card_url(agent_card: "AgentCard", base_url: str) -> "AgentCard": + """ + Fix the agent card URL if it contains a localhost/internal address. + + Many A2A agents are deployed with agent cards that contain internal URLs + like "http://0.0.0.0:8001/" or "http://localhost:8000/". This function + replaces such URLs with the provided base_url. + + Args: + agent_card: The agent card to fix + base_url: The base URL to use as replacement + + Returns: + The agent card with the URL fixed if necessary + """ + card_url = getattr(agent_card, "url", None) + + if card_url and is_localhost_or_internal_url(card_url): + # Normalize base_url to ensure it ends with / + fixed_url = base_url.rstrip("/") + "/" + agent_card.url = fixed_url + + return agent_card + + class LiteLLMA2ACardResolver(_A2ACardResolver): # type: ignore[misc] """ Custom A2A card resolver that supports multiple well-known paths. - + Extends the base A2ACardResolver to try both: - /.well-known/agent-card.json (standard) - /.well-known/agent.json (previous/alternative) """ - + async def get_agent_card( self, relative_card_path: Optional[str] = None, @@ -42,17 +89,17 @@ async def get_agent_card( ) -> "AgentCard": """ Fetch the agent card, trying multiple well-known paths. - + First tries the standard path, then falls back to the previous path. - + Args: relative_card_path: Optional path to the agent card endpoint. If None, tries both well-known paths. http_kwargs: Optional dictionary of keyword arguments to pass to httpx.get - + Returns: AgentCard from the A2A agent - + Raises: A2AClientHTTPError or A2AClientJSONError if both paths fail """ @@ -62,13 +109,13 @@ async def get_agent_card( relative_card_path=relative_card_path, http_kwargs=http_kwargs, ) - + # Try both well-known paths paths = [ AGENT_CARD_WELL_KNOWN_PATH, PREV_AGENT_CARD_WELL_KNOWN_PATH, ] - + last_error = None for path in paths: try: @@ -85,11 +132,11 @@ async def get_agent_card( ) last_error = e continue - + # If we get here, all paths failed - re-raise the last error if last_error is not None: raise last_error - + # This shouldn't happen, but just in case raise Exception( f"Failed to fetch agent card from {self.base_url}. " diff --git a/litellm/a2a_protocol/exception_mapping_utils.py b/litellm/a2a_protocol/exception_mapping_utils.py new file mode 100644 index 00000000000..49dbb22b158 --- /dev/null +++ b/litellm/a2a_protocol/exception_mapping_utils.py @@ -0,0 +1,203 @@ +""" +A2A Protocol Exception Mapping Utils. + +Maps A2A SDK exceptions to LiteLLM A2A exception types. +""" + +from typing import TYPE_CHECKING, Any, Optional + +from litellm._logging import verbose_logger +from litellm.a2a_protocol.card_resolver import ( + fix_agent_card_url, + is_localhost_or_internal_url, +) +from litellm.a2a_protocol.exceptions import ( + A2AAgentCardError, + A2AConnectionError, + A2AError, + A2ALocalhostURLError, +) +from litellm.constants import CONNECTION_ERROR_PATTERNS + +if TYPE_CHECKING: + from a2a.client import A2AClient as A2AClientType + + +# Runtime import +A2A_SDK_AVAILABLE = False +try: + from a2a.client import A2AClient as _A2AClient # type: ignore[no-redef] + + A2A_SDK_AVAILABLE = True +except ImportError: + _A2AClient = None # type: ignore[assignment, misc] + + +class A2AExceptionCheckers: + """ + Helper class for checking various A2A error conditions. + """ + + @staticmethod + def is_connection_error(error_str: str) -> bool: + """ + Check if an error string indicates a connection error. + + Args: + error_str: The error string to check + + Returns: + True if the error indicates a connection issue + """ + if not isinstance(error_str, str): + return False + + error_str_lower = error_str.lower() + return any(pattern in error_str_lower for pattern in CONNECTION_ERROR_PATTERNS) + + @staticmethod + def is_localhost_url(url: Optional[str]) -> bool: + """ + Check if a URL is a localhost/internal URL. + + Args: + url: The URL to check + + Returns: + True if the URL is localhost/internal + """ + return is_localhost_or_internal_url(url) + + @staticmethod + def is_agent_card_error(error_str: str) -> bool: + """ + Check if an error string indicates an agent card error. + + Args: + error_str: The error string to check + + Returns: + True if the error is related to agent card fetching/parsing + """ + if not isinstance(error_str, str): + return False + + error_str_lower = error_str.lower() + agent_card_patterns = [ + "agent card", + "agent-card", + ".well-known", + "card not found", + "invalid agent", + ] + return any(pattern in error_str_lower for pattern in agent_card_patterns) + + +def map_a2a_exception( + original_exception: Exception, + card_url: Optional[str] = None, + api_base: Optional[str] = None, + model: Optional[str] = None, +) -> Exception: + """ + Map an A2A SDK exception to a LiteLLM A2A exception type. + + Args: + original_exception: The original exception from the A2A SDK + card_url: The URL from the agent card (if available) + api_base: The original API base URL + model: The model/agent name + + Returns: + A mapped LiteLLM A2A exception + + Raises: + A2ALocalhostURLError: If the error is a connection error to a localhost URL + A2AConnectionError: If the error is a general connection error + A2AAgentCardError: If the error is related to agent card issues + A2AError: For other A2A-related errors + """ + error_str = str(original_exception) + + # Check for localhost URL connection error (special case - retryable) + if ( + card_url + and api_base + and A2AExceptionCheckers.is_localhost_url(card_url) + and A2AExceptionCheckers.is_connection_error(error_str) + ): + raise A2ALocalhostURLError( + localhost_url=card_url, + base_url=api_base, + original_error=original_exception, + model=model, + ) + + # Check for agent card errors + if A2AExceptionCheckers.is_agent_card_error(error_str): + raise A2AAgentCardError( + message=error_str, + url=api_base, + model=model, + ) + + # Check for general connection errors + if A2AExceptionCheckers.is_connection_error(error_str): + raise A2AConnectionError( + message=error_str, + url=card_url or api_base, + model=model, + ) + + # Default: wrap in generic A2AError + raise A2AError( + message=error_str, + model=model, + ) + + +def handle_a2a_localhost_retry( + error: A2ALocalhostURLError, + agent_card: Any, + a2a_client: "A2AClientType", + is_streaming: bool = False, +) -> "A2AClientType": + """ + Handle A2ALocalhostURLError by fixing the URL and creating a new client. + + This is called when we catch an A2ALocalhostURLError and want to retry + with the corrected URL. + + Args: + error: The localhost URL error + agent_card: The agent card object to fix + a2a_client: The current A2A client + is_streaming: Whether this is a streaming request (for logging) + + Returns: + A new A2A client with the fixed URL + + Raises: + ImportError: If the A2A SDK is not installed + """ + if not A2A_SDK_AVAILABLE or _A2AClient is None: + raise ImportError( + "A2A SDK is required for localhost retry handling. " + "Install it with: pip install a2a" + ) + + request_type = "streaming " if is_streaming else "" + verbose_logger.warning( + f"A2A {request_type}request to '{error.localhost_url}' failed: {error.original_error}. " + f"Agent card contains localhost/internal URL. " + f"Retrying with base_url '{error.base_url}'." + ) + + # Fix the agent card URL + fix_agent_card_url(agent_card, error.base_url) + + # Create a new client with the fixed agent card (transport caches URL) + return _A2AClient( + httpx_client=a2a_client._transport.httpx_client, # type: ignore[union-attr] + agent_card=agent_card, + ) diff --git a/litellm/a2a_protocol/exceptions.py b/litellm/a2a_protocol/exceptions.py new file mode 100644 index 00000000000..546b23105be --- /dev/null +++ b/litellm/a2a_protocol/exceptions.py @@ -0,0 +1,150 @@ +""" +A2A Protocol Exceptions. + +Custom exception types for A2A protocol operations, following LiteLLM's exception pattern. +""" + +from typing import Optional + +import httpx + + +class A2AError(Exception): + """ + Base exception for A2A protocol errors. + + Follows the same pattern as LiteLLM's main exceptions. + """ + + def __init__( + self, + message: str, + status_code: int = 500, + llm_provider: str = "a2a_agent", + model: Optional[str] = None, + response: Optional[httpx.Response] = None, + litellm_debug_info: Optional[str] = None, + max_retries: Optional[int] = None, + num_retries: Optional[int] = None, + ): + self.status_code = status_code + self.message = f"litellm.A2AError: {message}" + self.llm_provider = llm_provider + self.model = model + self.litellm_debug_info = litellm_debug_info + self.max_retries = max_retries + self.num_retries = num_retries + self.response = response or httpx.Response( + status_code=self.status_code, + request=httpx.Request(method="POST", url="https://litellm.ai"), + ) + super().__init__(self.message) + + def __str__(self) -> str: + _message = self.message + if self.num_retries: + _message += f" LiteLLM Retried: {self.num_retries} times" + if self.max_retries: + _message += f", LiteLLM Max Retries: {self.max_retries}" + return _message + + def __repr__(self) -> str: + return self.__str__() + + +class A2AConnectionError(A2AError): + """ + Raised when connection to an A2A agent fails. + + This typically occurs when: + - The agent is unreachable + - The agent card contains a localhost/internal URL + - Network issues prevent connection + """ + + def __init__( + self, + message: str, + url: Optional[str] = None, + model: Optional[str] = None, + response: Optional[httpx.Response] = None, + litellm_debug_info: Optional[str] = None, + max_retries: Optional[int] = None, + num_retries: Optional[int] = None, + ): + self.url = url + super().__init__( + message=message, + status_code=503, + llm_provider="a2a_agent", + model=model, + response=response, + litellm_debug_info=litellm_debug_info, + max_retries=max_retries, + num_retries=num_retries, + ) + + +class A2AAgentCardError(A2AError): + """ + Raised when there's an issue with the agent card. + + This includes: + - Failed to fetch agent card + - Invalid agent card format + - Missing required fields + """ + + def __init__( + self, + message: str, + url: Optional[str] = None, + model: Optional[str] = None, + response: Optional[httpx.Response] = None, + litellm_debug_info: Optional[str] = None, + ): + self.url = url + super().__init__( + message=message, + status_code=404, + llm_provider="a2a_agent", + model=model, + response=response, + litellm_debug_info=litellm_debug_info, + ) + + +class A2ALocalhostURLError(A2AConnectionError): + """ + Raised when an agent card contains a localhost/internal URL. + + Many A2A agents are deployed with agent cards that contain internal URLs + like "http://0.0.0.0:8001/" or "http://localhost:8000/". This error + indicates that the URL needs to be corrected and the request should be retried. + + Attributes: + localhost_url: The localhost/internal URL found in the agent card + base_url: The public base URL that should be used instead + original_error: The original connection error that was raised + """ + + def __init__( + self, + localhost_url: str, + base_url: str, + original_error: Optional[Exception] = None, + model: Optional[str] = None, + ): + self.localhost_url = localhost_url + self.base_url = base_url + self.original_error = original_error + + message = ( + f"Agent card contains localhost/internal URL '{localhost_url}'. " + f"Retrying with base URL '{base_url}'." + ) + super().__init__( + message=message, + url=localhost_url, + model=model, + ) diff --git a/litellm/a2a_protocol/main.py b/litellm/a2a_protocol/main.py index b326f9e7ed5..642dfaf023c 100644 --- a/litellm/a2a_protocol/main.py +++ b/litellm/a2a_protocol/main.py @@ -44,6 +44,11 @@ # Import our custom card resolver that supports multiple well-known paths from litellm.a2a_protocol.card_resolver import LiteLLMA2ACardResolver +from litellm.a2a_protocol.exception_mapping_utils import ( + handle_a2a_localhost_retry, + map_a2a_exception, +) +from litellm.a2a_protocol.exceptions import A2ALocalhostURLError # Use our custom resolver instead of the default A2A SDK resolver A2ACardResolver = LiteLLMA2ACardResolver @@ -244,10 +249,50 @@ async def asend_message( verbose_logger.info(f"A2A send_message request_id={request.id}, agent={agent_name}") - a2a_response = await a2a_client.send_message(request) + # Get agent card URL for localhost retry logic + agent_card = getattr(a2a_client, "_litellm_agent_card", None) or getattr( + a2a_client, "agent_card", None + ) + card_url = getattr(agent_card, "url", None) if agent_card else None + + # Retry loop: if connection fails due to localhost URL in agent card, retry with fixed URL + a2a_response = None + for _ in range(2): # max 2 attempts: original + 1 retry + try: + a2a_response = await a2a_client.send_message(request) + break # success, exit retry loop + except A2ALocalhostURLError as e: + # Localhost URL error - fix and retry + a2a_client = handle_a2a_localhost_retry( + error=e, + agent_card=agent_card, + a2a_client=a2a_client, + is_streaming=False, + ) + card_url = agent_card.url if agent_card else None + except Exception as e: + # Map exception - will raise A2ALocalhostURLError if applicable + try: + map_a2a_exception(e, card_url, api_base, model=agent_name) + except A2ALocalhostURLError as localhost_err: + # Localhost URL error - fix and retry + a2a_client = handle_a2a_localhost_retry( + error=localhost_err, + agent_card=agent_card, + a2a_client=a2a_client, + is_streaming=False, + ) + card_url = agent_card.url if agent_card else None + continue + except Exception: + # Re-raise the mapped exception + raise verbose_logger.info(f"A2A send_message completed, request_id={request.id}") + # a2a_response is guaranteed to be set if we reach here (loop breaks on success or raises) + assert a2a_response is not None + # Wrap in LiteLLM response type for _hidden_params support response = LiteLLMSendMessageResponse.from_a2a_response(a2a_response) @@ -307,6 +352,48 @@ def send_message( ) +def _build_streaming_logging_obj( + request: "SendStreamingMessageRequest", + agent_name: str, + agent_id: Optional[str], + litellm_params: Optional[Dict[str, Any]], + metadata: Optional[Dict[str, Any]], + proxy_server_request: Optional[Dict[str, Any]], +) -> Logging: + """Build logging object for streaming A2A requests.""" + start_time = datetime.datetime.now() + model = f"a2a_agent/{agent_name}" + + logging_obj = Logging( + model=model, + messages=[{"role": "user", "content": "streaming-request"}], + stream=False, + call_type="asend_message_streaming", + start_time=start_time, + litellm_call_id=str(request.id), + function_id=str(request.id), + ) + logging_obj.model = model + logging_obj.custom_llm_provider = "a2a_agent" + logging_obj.model_call_details["model"] = model + logging_obj.model_call_details["custom_llm_provider"] = "a2a_agent" + if agent_id: + logging_obj.model_call_details["agent_id"] = agent_id + + _litellm_params = litellm_params.copy() if litellm_params else {} + if metadata: + _litellm_params["metadata"] = metadata + if proxy_server_request: + _litellm_params["proxy_server_request"] = proxy_server_request + + logging_obj.litellm_params = _litellm_params + logging_obj.optional_params = _litellm_params + logging_obj.model_call_details["litellm_params"] = _litellm_params + logging_obj.model_call_details["metadata"] = metadata or {} + + return logging_obj + + async def asend_message_streaming( a2a_client: Optional["A2AClientType"] = None, request: Optional["SendStreamingMessageRequest"] = None, @@ -403,55 +490,72 @@ async def asend_message_streaming( verbose_logger.info(f"A2A send_message_streaming request_id={request.id}") - # Track for logging - start_time = datetime.datetime.now() - stream = a2a_client.send_message_streaming(request) - # Build logging object for streaming completion callbacks agent_card = getattr(a2a_client, "_litellm_agent_card", None) or getattr( a2a_client, "agent_card", None ) + card_url = getattr(agent_card, "url", None) if agent_card else None agent_name = getattr(agent_card, "name", "unknown") if agent_card else "unknown" - model = f"a2a_agent/{agent_name}" - - logging_obj = Logging( - model=model, - messages=[{"role": "user", "content": "streaming-request"}], - stream=False, # complete response logging after stream ends - call_type="asend_message_streaming", - start_time=start_time, - litellm_call_id=str(request.id), - function_id=str(request.id), - ) - logging_obj.model = model - logging_obj.custom_llm_provider = "a2a_agent" - logging_obj.model_call_details["model"] = model - logging_obj.model_call_details["custom_llm_provider"] = "a2a_agent" - if agent_id: - logging_obj.model_call_details["agent_id"] = agent_id - # Propagate litellm_params for spend logging (includes cost_per_query, etc.) - _litellm_params = litellm_params.copy() if litellm_params else {} - # Merge metadata into litellm_params.metadata (required for proxy cost tracking) - if metadata: - _litellm_params["metadata"] = metadata - if proxy_server_request: - _litellm_params["proxy_server_request"] = proxy_server_request - - logging_obj.litellm_params = _litellm_params - logging_obj.optional_params = _litellm_params # used by cost calc - logging_obj.model_call_details["litellm_params"] = _litellm_params - logging_obj.model_call_details["metadata"] = metadata or {} - - iterator = A2AStreamingIterator( - stream=stream, + logging_obj = _build_streaming_logging_obj( request=request, - logging_obj=logging_obj, agent_name=agent_name, + agent_id=agent_id, + litellm_params=litellm_params, + metadata=metadata, + proxy_server_request=proxy_server_request, ) - async for chunk in iterator: - yield chunk + # Retry loop: if connection fails due to localhost URL in agent card, retry with fixed URL + # Connection errors in streaming typically occur on first chunk iteration + first_chunk = True + for attempt in range(2): # max 2 attempts: original + 1 retry + stream = a2a_client.send_message_streaming(request) + iterator = A2AStreamingIterator( + stream=stream, + request=request, + logging_obj=logging_obj, + agent_name=agent_name, + ) + + try: + first_chunk = True + async for chunk in iterator: + if first_chunk: + first_chunk = False # connection succeeded + yield chunk + return # stream completed successfully + except A2ALocalhostURLError as e: + # Only retry on first chunk, not mid-stream + if first_chunk and attempt == 0: + a2a_client = handle_a2a_localhost_retry( + error=e, + agent_card=agent_card, + a2a_client=a2a_client, + is_streaming=True, + ) + card_url = agent_card.url if agent_card else None + else: + raise + except Exception as e: + # Only map exception on first chunk + if first_chunk and attempt == 0: + try: + map_a2a_exception(e, card_url, api_base, model=agent_name) + except A2ALocalhostURLError as localhost_err: + # Localhost URL error - fix and retry + a2a_client = handle_a2a_localhost_retry( + error=localhost_err, + agent_card=agent_card, + a2a_client=a2a_client, + is_streaming=True, + ) + card_url = agent_card.url if agent_card else None + continue + except Exception: + # Re-raise the mapped exception + raise + raise async def create_a2a_client( diff --git a/litellm/anthropic_beta_headers_config.json b/litellm/anthropic_beta_headers_config.json new file mode 100644 index 00000000000..193091c0176 --- /dev/null +++ b/litellm/anthropic_beta_headers_config.json @@ -0,0 +1,30 @@ +{ + "description": "Unsupported Anthropic beta headers for each provider. Headers listed here will be dropped. Headers not listed are passed through as-is.", + "anthropic": [], + "azure_ai": [], + "bedrock_converse": [ + "prompt-caching-scope-2026-01-05", + "bash_20250124", + "bash_20241022", + "text_editor_20250124", + "text_editor_20241022", + "compact-2026-01-12", + "advanced-tool-use-2025-11-20", + "web-fetch-2025-09-10", + "code-execution-2025-08-25", + "skills-2025-10-02", + "files-api-2025-04-14" + ], + "bedrock": [ + "advanced-tool-use-2025-11-20", + "prompt-caching-scope-2026-01-05", + "structured-outputs-2025-11-13", + "web-fetch-2025-09-10", + "code-execution-2025-08-25", + "skills-2025-10-02", + "files-api-2025-04-14" + ], + "vertex_ai": [ + "prompt-caching-scope-2026-01-05" + ] +} diff --git a/litellm/anthropic_beta_headers_manager.py b/litellm/anthropic_beta_headers_manager.py new file mode 100644 index 00000000000..2643f4c03fa --- /dev/null +++ b/litellm/anthropic_beta_headers_manager.py @@ -0,0 +1,221 @@ +""" +Centralized manager for Anthropic beta headers across different providers. + +This module provides utilities to: +1. Load beta header configuration from JSON (lists unsupported headers per provider) +2. Filter out unsupported beta headers +3. Handle provider-specific header name mappings (e.g., advanced-tool-use -> tool-search-tool) + +Design: +- JSON config lists UNSUPPORTED headers for each provider +- Headers not in the unsupported list are passed through +- Header mappings allow renaming headers for specific providers +""" + +import json +import os +from typing import Dict, List, Optional, Set + +from litellm.litellm_core_utils.litellm_logging import verbose_logger + +# Cache for the loaded configuration +_BETA_HEADERS_CONFIG: Optional[Dict] = None + + +def _load_beta_headers_config() -> Dict: + """ + Load the beta headers configuration from JSON file. + Uses caching to avoid repeated file reads. + + Returns: + Dict containing the beta headers configuration + """ + global _BETA_HEADERS_CONFIG + + if _BETA_HEADERS_CONFIG is not None: + return _BETA_HEADERS_CONFIG + + config_path = os.path.join( + os.path.dirname(__file__), + "anthropic_beta_headers_config.json" + ) + + try: + with open(config_path, "r") as f: + _BETA_HEADERS_CONFIG = json.load(f) + verbose_logger.debug(f"Loaded beta headers config from {config_path}") + return _BETA_HEADERS_CONFIG + except Exception as e: + verbose_logger.error(f"Failed to load beta headers config: {e}") + # Return empty config as fallback + return { + "anthropic": [], + "azure_ai": [], + "bedrock": [], + "bedrock_converse": [], + "vertex_ai": [] + } + + +def get_provider_name(provider: str) -> str: + """ + Resolve provider aliases to canonical provider names. + + Args: + provider: Provider name (may be an alias) + + Returns: + Canonical provider name + """ + config = _load_beta_headers_config() + aliases = config.get("provider_aliases", {}) + return aliases.get(provider, provider) + + +def filter_and_transform_beta_headers( + beta_headers: List[str], + provider: str, +) -> List[str]: + """ + Filter beta headers based on provider's unsupported list. + + This function: + 1. Removes headers that are in the provider's unsupported list + 2. Passes through all other headers as-is + + Note: Header transformations/mappings (e.g., advanced-tool-use -> tool-search-tool) + are handled in each provider's transformation code, not here. + + Args: + beta_headers: List of Anthropic beta header values + provider: Provider name (e.g., "anthropic", "bedrock", "vertex_ai") + + Returns: + List of filtered beta headers for the provider + """ + if not beta_headers: + return [] + + config = _load_beta_headers_config() + provider = get_provider_name(provider) + + # Get unsupported headers for this provider + unsupported_headers = set(config.get(provider, [])) + + filtered_headers: Set[str] = set() + + for header in beta_headers: + header = header.strip() + + # Skip if header is unsupported + if header in unsupported_headers: + verbose_logger.debug( + f"Dropping unsupported beta header '{header}' for provider '{provider}'" + ) + continue + + # Pass through as-is + filtered_headers.add(header) + + return sorted(list(filtered_headers)) + + +def is_beta_header_supported( + beta_header: str, + provider: str, +) -> bool: + """ + Check if a specific beta header is supported by a provider. + + Args: + beta_header: The Anthropic beta header value + provider: Provider name + + Returns: + True if the header is supported (not in unsupported list), False otherwise + """ + config = _load_beta_headers_config() + provider = get_provider_name(provider) + unsupported_headers = set(config.get(provider, [])) + return beta_header not in unsupported_headers + + +def get_provider_beta_header( + anthropic_beta_header: str, + provider: str, +) -> Optional[str]: + """ + Check if a beta header is supported by a provider. + + Note: This does NOT handle header transformations/mappings. + Those are handled in each provider's transformation code. + + Args: + anthropic_beta_header: The Anthropic beta header value + provider: Provider name + + Returns: + The original header if supported, or None if unsupported + """ + config = _load_beta_headers_config() + provider = get_provider_name(provider) + + # Check if unsupported + unsupported_headers = set(config.get(provider, [])) + if anthropic_beta_header in unsupported_headers: + return None + + return anthropic_beta_header + + +def update_headers_with_filtered_beta( + headers: dict, + provider: str, +) -> dict: + """ + Update headers dict by filtering and transforming anthropic-beta header values. + Modifies the headers dict in place and returns it. + + Args: + headers: Request headers dict (will be modified in place) + provider: Provider name + + Returns: + Updated headers dict + """ + existing_beta = headers.get("anthropic-beta") + if not existing_beta: + return headers + + # Parse existing beta headers + beta_values = [b.strip() for b in existing_beta.split(",") if b.strip()] + + # Filter and transform based on provider + filtered_beta_values = filter_and_transform_beta_headers( + beta_headers=beta_values, + provider=provider, + ) + + # Update or remove the header + if filtered_beta_values: + headers["anthropic-beta"] = ",".join(filtered_beta_values) + else: + # Remove the header if no values remain + headers.pop("anthropic-beta", None) + + return headers + + +def get_unsupported_headers(provider: str) -> List[str]: + """ + Get all beta headers that are unsupported by a provider. + + Args: + provider: Provider name + + Returns: + List of unsupported Anthropic beta header names + """ + config = _load_beta_headers_config() + provider = get_provider_name(provider) + return config.get(provider, []) diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.py index ea7e3f5a979..03d09ecc041 100644 --- a/litellm/caching/redis_cache.py +++ b/litellm/caching/redis_cache.py @@ -1123,7 +1123,7 @@ async def test_connection(self) -> dict: redis_client = redis_async.Redis(**self.redis_kwargs) # Test the connection - ping_result = await redis_client.ping() + ping_result = await redis_client.ping() # type: ignore[misc] # Close the connection await redis_client.aclose() # type: ignore[attr-defined] diff --git a/litellm/caching/redis_cluster_cache.py b/litellm/caching/redis_cluster_cache.py index 91fcf1d7288..664578c8700 100644 --- a/litellm/caching/redis_cluster_cache.py +++ b/litellm/caching/redis_cluster_cache.py @@ -83,7 +83,7 @@ async def test_connection(self) -> dict: ) # Test the connection - ping_result = await redis_client.ping() # type: ignore[attr-defined] + ping_result = await redis_client.ping() # type: ignore[attr-defined, misc] # Close the connection await redis_client.aclose() # type: ignore[attr-defined] diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py index 57bd05124aa..753a94295b3 100644 --- a/litellm/completion_extras/litellm_responses_transformation/transformation.py +++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py @@ -329,6 +329,9 @@ def transform_request( else: request_data[key] = value + if headers: + request_data["extra_headers"] = headers + return request_data @staticmethod diff --git a/litellm/constants.py b/litellm/constants.py index 3c84547d7ce..3c618723d64 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -67,6 +67,25 @@ os.getenv("DEFAULT_REASONING_EFFORT_DISABLE_THINKING_BUDGET", 0) ) +# MCP Semantic Tool Filter Defaults +DEFAULT_MCP_SEMANTIC_FILTER_EMBEDDING_MODEL = str( + os.getenv("DEFAULT_MCP_SEMANTIC_FILTER_EMBEDDING_MODEL", "text-embedding-3-small") +) +DEFAULT_MCP_SEMANTIC_FILTER_TOP_K = int( + os.getenv("DEFAULT_MCP_SEMANTIC_FILTER_TOP_K", 10) +) +DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_THRESHOLD = float( + os.getenv("DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_THRESHOLD", 0.3) +) +MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH = int( + os.getenv("MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH", 150) +) + +LITELLM_UI_ALLOW_HEADERS = [ + "x-litellm-semantic-filter", + "x-litellm-semantic-filter-tools", +] + # Gemini model-specific minimal thinking budget constants DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_FLASH = int( os.getenv("DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_FLASH", 1) @@ -85,6 +104,9 @@ os.getenv("DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET", 128) ) +# Provider-specific API base URLs +XAI_API_BASE = "https://api.x.ai/v1" + DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET = int( os.getenv("DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET", 1024) ) @@ -284,6 +306,22 @@ #### Networking settings #### request_timeout: float = float(os.getenv("REQUEST_TIMEOUT", 6000)) # time in seconds DEFAULT_A2A_AGENT_TIMEOUT: float = float(os.getenv("DEFAULT_A2A_AGENT_TIMEOUT", 6000)) # 10 minutes +# Patterns that indicate a localhost/internal URL in A2A agent cards that should be +# replaced with the original base_url. This is a common misconfiguration where +# developers deploy agents with development URLs in their agent cards. +LOCALHOST_URL_PATTERNS: List[str] = [ + "localhost", + "127.0.0.1", + "0.0.0.0", + "[::1]", # IPv6 localhost +] +# Patterns in error messages that indicate a connection failure +CONNECTION_ERROR_PATTERNS: List[str] = [ + "connect", + "connection", + "network", + "refused", +] STREAM_SSE_DONE_STRING: str = "[DONE]" STREAM_SSE_DATA_PREFIX: str = "data: " ### SPEND TRACKING ### @@ -948,6 +986,8 @@ "openai.gpt-oss-120b-1:0", "anthropic.claude-haiku-4-5-20251001-v1:0", "anthropic.claude-sonnet-4-5-20250929-v1:0", + "anthropic.claude-opus-4-6-v1:0", + "anthropic.claude-opus-4-6-v1", "anthropic.claude-opus-4-1-20250805-v1:0", "anthropic.claude-opus-4-20250514-v1:0", "anthropic.claude-sonnet-4-20250514-v1:0", diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.py index 3e8f9bc337b..5e21ff9754f 100644 --- a/litellm/experimental_mcp_client/client.py +++ b/litellm/experimental_mcp_client/client.py @@ -209,6 +209,8 @@ def _get_auth_headers(self) -> dict: headers["X-API-Key"] = self._mcp_auth_value elif self.auth_type == MCPAuth.authorization: headers["Authorization"] = self._mcp_auth_value + elif self.auth_type == MCPAuth.oauth2: + headers["Authorization"] = f"Bearer {self._mcp_auth_value}" elif isinstance(self._mcp_auth_value, dict): headers.update(self._mcp_auth_value) diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.py index 0c36e15db01..8fb3e132ded 100644 --- a/litellm/integrations/SlackAlerting/slack_alerting.py +++ b/litellm/integrations/SlackAlerting/slack_alerting.py @@ -1378,6 +1378,11 @@ async def send_alert( """ if self.alerting is None: return + + # Start periodic flush if not already started + if not self.periodic_started and self.alerting is not None and len(self.alerting) > 0: + asyncio.create_task(self.periodic_flush()) + self.periodic_started = True if ( "webhook" in self.alerting diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py index a5bb530fc56..bbd55a59bce 100644 --- a/litellm/integrations/custom_guardrail.py +++ b/litellm/integrations/custom_guardrail.py @@ -268,6 +268,7 @@ def get_guardrail_from_metadata( """ Returns the guardrail(s) to be run from the metadata or root """ + if "guardrails" in data: return data["guardrails"] metadata = data.get("litellm_metadata") or data.get("metadata", {}) @@ -475,11 +476,18 @@ def get_guardrail_dynamic_request_body_params(self, request_data: dict) -> dict: guardrail_config: DynamicGuardrailParams = DynamicGuardrailParams( **guardrail[self.guardrail_name] ) + extra_body = guardrail_config.get("extra_body", {}) if self._validate_premium_user() is not True: + if isinstance(extra_body, dict) and extra_body: + verbose_logger.warning( + "Guardrail %s: ignoring dynamic extra_body keys %s because premium_user is False", + self.guardrail_name, + list(extra_body.keys()), + ) return {} # Return the extra_body if it exists, otherwise empty dict - return guardrail_config.get("extra_body", {}) + return extra_body return {} diff --git a/litellm/integrations/email_templates/templates.py b/litellm/integrations/email_templates/templates.py index 5de23db0f24..091351df2bb 100644 --- a/litellm/integrations/email_templates/templates.py +++ b/litellm/integrations/email_templates/templates.py @@ -85,6 +85,30 @@ The LiteLLM team
""" +TEAM_SOFT_BUDGET_ALERT_EMAIL_TEMPLATE = """ + LiteLLM Logo + +

Hi {team_alias} team member,
+ + Your LiteLLM team has crossed its soft budget limit of {soft_budget}.

+ + Current Spend: {spend}
+ Soft Budget: {soft_budget}
+ {max_budget_info} + +

+ ⚠️ Note: Your API requests will continue to work, but you should monitor your usage closely. + If you reach your maximum budget, requests will be rejected. +

+ + You can view your usage and manage your budget in the LiteLLM Dashboard.

+ + If you have any questions, please send an email to {email_support_contact}

+ + Best,
+ The LiteLLM team
+""" + MAX_BUDGET_ALERT_EMAIL_TEMPLATE = """ LiteLLM Logo diff --git a/litellm/integrations/langfuse/langfuse_otel.py b/litellm/integrations/langfuse/langfuse_otel.py index 08493a0e8ec..8955d3619f7 100644 --- a/litellm/integrations/langfuse/langfuse_otel.py +++ b/litellm/integrations/langfuse/langfuse_otel.py @@ -8,9 +8,8 @@ from litellm.integrations.langfuse.langfuse_otel_attributes import ( LangfuseLLMObsOTELAttributes, ) -from litellm.integrations.opentelemetry import OpenTelemetry +from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig from litellm.types.integrations.langfuse_otel import ( - LangfuseOtelConfig, LangfuseSpanAttributes, ) from litellm.types.utils import StandardCallbackDynamicParams @@ -18,17 +17,8 @@ if TYPE_CHECKING: from opentelemetry.trace import Span as _Span - from litellm.integrations.opentelemetry import ( - OpenTelemetryConfig as _OpenTelemetryConfig, - ) - from litellm.types.integrations.arize import Protocol as _Protocol - - Protocol = _Protocol - OpenTelemetryConfig = _OpenTelemetryConfig Span = Union[_Span, Any] else: - Protocol = Any - OpenTelemetryConfig = Any Span = Any @@ -37,8 +27,12 @@ class LangfuseOtelLogger(OpenTelemetry): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) + def __init__(self, config=None, *args, **kwargs): + # Prevent LangfuseOtelLogger from modifying global environment variables by constructing config manually + # and passing it to the parent OpenTelemetry class + if config is None: + config = self._create_open_telemetry_config_from_langfuse_env() + super().__init__(config=config, *args, **kwargs) @staticmethod def set_langfuse_otel_attributes(span: Span, kwargs, response_obj): @@ -114,6 +108,10 @@ def _set_metadata_attributes(span: Span, metadata: dict): for key, enum_attr in mapping.items(): if key in metadata and metadata[key] is not None: value = metadata[key] + if key == "trace_id" and isinstance(value, str): + # trace_id must be 32 hex char no dashes for langfuse : Litellm sends uuid with dashes (might be breaking at some point) + value = value.replace("-", "") + if isinstance(value, (list, dict)): try: value = json.dumps(value) @@ -265,8 +263,47 @@ def _get_langfuse_otel_host() -> Optional[str]: """ return os.environ.get("LANGFUSE_OTEL_HOST") or os.environ.get("LANGFUSE_HOST") + def _create_open_telemetry_config_from_langfuse_env(self) -> OpenTelemetryConfig: + """ + Creates OpenTelemetryConfig from Langfuse environment variables. + Does NOT modify global environment variables. + """ + from litellm.integrations.opentelemetry import OpenTelemetryConfig + + public_key = os.environ.get("LANGFUSE_PUBLIC_KEY", None) + secret_key = os.environ.get("LANGFUSE_SECRET_KEY", None) + + if not public_key or not secret_key: + # If no keys, return default from env (likely logging to console or something else) + return OpenTelemetryConfig.from_env() + + # Determine endpoint - default to US cloud + langfuse_host = LangfuseOtelLogger._get_langfuse_otel_host() + + if langfuse_host: + # If LANGFUSE_HOST is provided, construct OTEL endpoint from it + if not langfuse_host.startswith("http"): + langfuse_host = "https://" + langfuse_host + endpoint = f"{langfuse_host.rstrip('/')}/api/public/otel" + verbose_logger.debug(f"Using Langfuse OTEL endpoint from host: {endpoint}") + else: + # Default to US cloud endpoint + endpoint = LANGFUSE_CLOUD_US_ENDPOINT + verbose_logger.debug(f"Using Langfuse US cloud endpoint: {endpoint}") + + auth_header = LangfuseOtelLogger._get_langfuse_authorization_header( + public_key=public_key, secret_key=secret_key + ) + otlp_auth_headers = f"Authorization={auth_header}" + + return OpenTelemetryConfig( + exporter="otlp_http", + endpoint=endpoint, + headers=otlp_auth_headers, + ) + @staticmethod - def get_langfuse_otel_config() -> LangfuseOtelConfig: + def get_langfuse_otel_config() -> "OpenTelemetryConfig": """ Retrieves the Langfuse OpenTelemetry configuration based on environment variables. @@ -276,7 +313,7 @@ def get_langfuse_otel_config() -> LangfuseOtelConfig: LANGFUSE_HOST: Optional. Custom Langfuse host URL. Defaults to US cloud. Returns: - LangfuseOtelConfig: A Pydantic model containing Langfuse OTEL configuration. + OpenTelemetryConfig: A Pydantic model containing Langfuse OTEL configuration. Raises: ValueError: If required keys are missing. @@ -308,12 +345,14 @@ def get_langfuse_otel_config() -> LangfuseOtelConfig: ) otlp_auth_headers = f"Authorization={auth_header}" - # Set standard OTEL environment variables - os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = endpoint - os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = otlp_auth_headers + # Prevent modification of global env vars which causes leakage + # os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = endpoint + # os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = otlp_auth_headers - return LangfuseOtelConfig( - otlp_auth_headers=otlp_auth_headers, protocol="otlp_http" + return OpenTelemetryConfig( + exporter="otlp_http", + endpoint=endpoint, + headers=otlp_auth_headers, ) @staticmethod diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.py index 18898be7dce..296a88f9a0b 100644 --- a/litellm/integrations/opentelemetry.py +++ b/litellm/integrations/opentelemetry.py @@ -599,9 +599,9 @@ def get_tracer_to_use_for_request(self, kwargs: dict) -> Tracer: def _get_dynamic_otel_headers_from_kwargs(self, kwargs) -> Optional[dict]: """Extract dynamic headers from kwargs if available.""" - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - kwargs.get("standard_callback_dynamic_params") - ) + standard_callback_dynamic_params: Optional[ + StandardCallbackDynamicParams + ] = kwargs.get("standard_callback_dynamic_params") if not standard_callback_dynamic_params: return None @@ -619,7 +619,9 @@ def _get_tracer_with_dynamic_headers(self, dynamic_headers: dict): # Prevents thread exhaustion by reusing providers for the same credential sets (e.g. per-team keys) cache_key = str(sorted(dynamic_headers.items())) if cache_key in self._tracer_provider_cache: - return self._tracer_provider_cache[cache_key].get_tracer(LITELLM_TRACER_NAME) + return self._tracer_provider_cache[cache_key].get_tracer( + LITELLM_TRACER_NAME + ) # Create a temporary tracer provider with dynamic headers temp_provider = TracerProvider(resource=self._get_litellm_resource(self.config)) @@ -674,7 +676,10 @@ def _handle_success(self, kwargs, response_obj, start_time, end_time): kwargs, response_obj, start_time, end_time, span ) # Ensure proxy-request parent span is annotated with the actual operation kind - if parent_span is not None and parent_span.name == LITELLM_PROXY_REQUEST_SPAN_NAME: + if ( + parent_span is not None + and parent_span.name == LITELLM_PROXY_REQUEST_SPAN_NAME + ): self.set_attributes(parent_span, kwargs, response_obj) else: # Do not create primary span (keep hierarchy shallow when parent exists) @@ -1003,14 +1008,11 @@ def _emit_semantic_logs(self, kwargs, response_obj, span: Span): # TODO: Refactor to use the proper OTEL Logs API instead of directly creating SDK LogRecords from opentelemetry._logs import SeverityNumber, get_logger, get_logger_provider + try: - from opentelemetry.sdk._logs import ( - LogRecord as SdkLogRecord, # type: ignore[attr-defined] # OTEL < 1.39.0 - ) + from opentelemetry.sdk._logs import LogRecord as SdkLogRecord # type: ignore[attr-defined] # OTEL < 1.39.0 except ImportError: - from opentelemetry.sdk._logs._internal import ( - LogRecord as SdkLogRecord, # OTEL >= 1.39.0 - ) + from opentelemetry.sdk._logs._internal import LogRecord as SdkLogRecord # type: ignore[attr-defined, no-redef] # OTEL >= 1.39.0 otel_logger = get_logger(LITELLM_LOGGER_NAME) @@ -1618,7 +1620,6 @@ def set_attributes( # noqa: PLR0915 for idx, choice in enumerate(response_obj.get("choices")): if choice.get("finish_reason"): - message = choice.get("message") tool_calls = message.get("tool_calls") if tool_calls: @@ -1631,7 +1632,9 @@ def set_attributes( # noqa: PLR0915 ) except Exception as e: - self.handle_callback_failure(callback_name=self.callback_name or "opentelemetry") + self.handle_callback_failure( + callback_name=self.callback_name or "opentelemetry" + ) verbose_logger.exception( "OpenTelemetry logging error in set_attributes %s", str(e) ) @@ -1722,6 +1725,7 @@ def _transform_choices_to_otel_semantic_conventions( def set_raw_request_attributes(self, span: Span, kwargs, response_obj): try: + self.set_attributes(span, kwargs, response_obj) kwargs.get("optional_params", {}) litellm_params = kwargs.get("litellm_params", {}) or {} custom_llm_provider = litellm_params.get("custom_llm_provider", "Unknown") diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py index 2c897cb0692..0a61dab0680 100644 --- a/litellm/integrations/prometheus.py +++ b/litellm/integrations/prometheus.py @@ -1,6 +1,7 @@ # used for /metrics endpoint on LiteLLM Proxy #### What this does #### # On success, log events to Prometheus +import asyncio import os import sys from datetime import datetime, timedelta @@ -1188,28 +1189,34 @@ async def _increment_remaining_budget_metrics( _user_spend = _metadata.get("user_api_key_user_spend", None) _user_max_budget = _metadata.get("user_api_key_user_max_budget", None) - await self._set_api_key_budget_metrics_after_api_request( - user_api_key=user_api_key, - user_api_key_alias=user_api_key_alias, - response_cost=response_cost, - key_max_budget=_api_key_max_budget, - key_spend=_api_key_spend, - ) - - await self._set_team_budget_metrics_after_api_request( - user_api_team=user_api_team, - user_api_team_alias=user_api_team_alias, - team_spend=_team_spend, - team_max_budget=_team_max_budget, - response_cost=response_cost, - ) - - await self._set_user_budget_metrics_after_api_request( - user_id=user_id, - user_spend=_user_spend, - user_max_budget=_user_max_budget, - response_cost=response_cost, + results = await asyncio.gather( + self._set_api_key_budget_metrics_after_api_request( + user_api_key=user_api_key, + user_api_key_alias=user_api_key_alias, + response_cost=response_cost, + key_max_budget=_api_key_max_budget, + key_spend=_api_key_spend, + ), + self._set_team_budget_metrics_after_api_request( + user_api_team=user_api_team, + user_api_team_alias=user_api_team_alias, + team_spend=_team_spend, + team_max_budget=_team_max_budget, + response_cost=response_cost, + ), + self._set_user_budget_metrics_after_api_request( + user_id=user_id, + user_spend=_user_spend, + user_max_budget=_user_max_budget, + response_cost=response_cost, + ), + return_exceptions=True, ) + for i, r in enumerate(results): + if isinstance(r, Exception): + verbose_logger.debug( + f"[Non-Blocking] Prometheus: Budget metric lookup {['key', 'team', 'user'][i]} failed: {r}" + ) def _increment_top_level_request_and_spend_metrics( self, @@ -1683,6 +1690,108 @@ async def async_post_call_success_hook( ) pass + def _safe_get(self, obj: Any, key: str, default: Any = None) -> Any: + """Get value from dict or Pydantic model.""" + if obj is None: + return default + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + def _extract_deployment_failure_label_values( + self, request_kwargs: dict + ) -> Dict[str, Optional[str]]: + """ + Extract label values for deployment failure metrics from all available + sources in request_kwargs. Falls back to litellm_params metadata and + user_api_key_auth when standard_logging_payload has None values. + """ + standard_logging_payload = ( + request_kwargs.get("standard_logging_object", {}) or {} + ) + _litellm_params = request_kwargs.get("litellm_params", {}) or {} + _metadata_raw = self._safe_get(standard_logging_payload, "metadata") or {} + if isinstance(_metadata_raw, dict): + _metadata = _metadata_raw + else: + _metadata = { + "user_api_key_alias": getattr( + _metadata_raw, "user_api_key_alias", None + ), + "user_api_key_team_id": getattr( + _metadata_raw, "user_api_key_team_id", None + ), + "user_api_key_team_alias": getattr( + _metadata_raw, "user_api_key_team_alias", None + ), + "user_api_key_hash": getattr(_metadata_raw, "user_api_key_hash", None), + "requester_ip_address": getattr( + _metadata_raw, "requester_ip_address", None + ), + "user_agent": getattr(_metadata_raw, "user_agent", None), + } + _litellm_params_metadata = _litellm_params.get("metadata", {}) or {} + + # Extract user_api_key_auth if present (proxy injects this, skipped in merge) + user_api_key_auth = _litellm_params_metadata.get("user_api_key_auth") + + def _get_api_key_alias() -> Optional[str]: + val = _metadata.get("user_api_key_alias") + if val is not None: + return val + val = _litellm_params_metadata.get("user_api_key_alias") + if val is not None: + return val + if user_api_key_auth is not None: + return getattr(user_api_key_auth, "key_alias", None) + return None + + def _get_team_id() -> Optional[str]: + val = _metadata.get("user_api_key_team_id") + if val is not None: + return val + val = _litellm_params_metadata.get("user_api_key_team_id") + if val is not None: + return val + if user_api_key_auth is not None: + return getattr(user_api_key_auth, "team_id", None) + return None + + def _get_team_alias() -> Optional[str]: + val = _metadata.get("user_api_key_team_alias") + if val is not None: + return val + val = _litellm_params_metadata.get("user_api_key_team_alias") + if val is not None: + return val + if user_api_key_auth is not None: + return getattr(user_api_key_auth, "team_alias", None) + return None + + def _get_hashed_api_key() -> Optional[str]: + val = _metadata.get("user_api_key_hash") + if val is not None: + return val + val = _litellm_params_metadata.get("user_api_key_hash") + if val is not None: + return val + if user_api_key_auth is not None: + return getattr(user_api_key_auth, "api_key", None) or getattr( + user_api_key_auth, "api_key_hash", None + ) + return None + + return { + "api_key_alias": _get_api_key_alias(), + "team": _get_team_id(), + "team_alias": _get_team_alias(), + "hashed_api_key": _get_hashed_api_key(), + "client_ip": _metadata.get("requester_ip_address") + or _litellm_params_metadata.get("requester_ip_address"), + "user_agent": _metadata.get("user_agent") + or _litellm_params_metadata.get("user_agent"), + } + def set_llm_deployment_failure_metrics(self, request_kwargs: dict): """ Sets Failure metrics when an LLM API call fails @@ -1707,6 +1816,21 @@ def set_llm_deployment_failure_metrics(self, request_kwargs: dict): model_id = standard_logging_payload.get("model_id", None) exception = request_kwargs.get("exception", None) + # Fallback: model_id from litellm_metadata.model_info + if model_id is None: + _model_info = ( + (_litellm_params.get("litellm_metadata") or {}).get("model_info") + or (_litellm_params.get("metadata") or {}).get("model_info") + or {} + ) + model_id = _model_info.get("id") + + # Fallback: model_group from litellm_metadata + if model_group is None: + model_group = (_litellm_params.get("litellm_metadata") or {}).get( + "model_group" + ) or (_litellm_params.get("metadata") or {}).get("model_group") + llm_provider = _litellm_params.get("custom_llm_provider", None) if self._should_skip_metrics_for_invalid_key( @@ -1714,9 +1838,37 @@ def set_llm_deployment_failure_metrics(self, request_kwargs: dict): standard_logging_payload=standard_logging_payload, ): return - hashed_api_key = standard_logging_payload.get("metadata", {}).get( + + # Extract context labels from all available sources (fix for None labels) + fallback_values = self._extract_deployment_failure_label_values( + request_kwargs + ) + _metadata = standard_logging_payload.get("metadata", {}) or {} + hashed_api_key = fallback_values.get("hashed_api_key") or _metadata.get( "user_api_key_hash" ) + api_key_alias = fallback_values.get("api_key_alias") or _metadata.get( + "user_api_key_alias" + ) + team = fallback_values.get("team") or _metadata.get("user_api_key_team_id") + team_alias = fallback_values.get("team_alias") or _metadata.get( + "user_api_key_team_alias" + ) + client_ip = fallback_values.get("client_ip") or _metadata.get( + "requester_ip_address" + ) + user_agent = fallback_values.get("user_agent") or _metadata.get( + "user_agent" + ) + + # exception_status: prefer status_code, fallback to exception class for known types + exception_status = None + if exception is not None: + exception_status = str(getattr(exception, "status_code", None)) + if exception_status == "None" or not exception_status: + code = getattr(exception, "code", None) + if code is not None: + exception_status = str(code) # Create enum_values for the label factory (always create for use in different metrics) enum_values = UserAPIKeyLabelValues( @@ -1724,26 +1876,18 @@ def set_llm_deployment_failure_metrics(self, request_kwargs: dict): model_id=model_id, api_base=api_base, api_provider=llm_provider, - exception_status=( - str(getattr(exception, "status_code", None)) if exception else None - ), + exception_status=exception_status, exception_class=( self._get_exception_class_name(exception) if exception else None ), - requested_model=model_group, + requested_model=model_group or litellm_model_name, hashed_api_key=hashed_api_key, - api_key_alias=standard_logging_payload["metadata"][ - "user_api_key_alias" - ], - team=standard_logging_payload["metadata"]["user_api_key_team_id"], - team_alias=standard_logging_payload["metadata"][ - "user_api_key_team_alias" - ], + api_key_alias=api_key_alias, + team=team, + team_alias=team_alias, tags=standard_logging_payload.get("request_tags", []), - client_ip=standard_logging_payload["metadata"].get( - "requester_ip_address" - ), - user_agent=standard_logging_payload["metadata"].get("user_agent"), + client_ip=client_ip, + user_agent=user_agent, ) """ @@ -2761,12 +2905,14 @@ async def _assemble_user_object( max_budget=max_budget, ) try: + # Note: Setting check_db_only=True bypasses cache and hits DB on every request, + # causing huge latency increase and CPU spikes. Keep check_db_only=False. user_info = await get_user_object( user_id=user_id, prisma_client=prisma_client, user_api_key_cache=user_api_key_cache, user_id_upsert=False, - check_db_only=True, + check_db_only=False, ) except Exception as e: verbose_logger.debug( diff --git a/litellm/litellm_core_utils/core_helpers.py b/litellm/litellm_core_utils/core_helpers.py index 00695cbfb5b..7c8e2ebeaff 100644 --- a/litellm/litellm_core_utils/core_helpers.py +++ b/litellm/litellm_core_utils/core_helpers.py @@ -94,8 +94,8 @@ def map_finish_reason( return "length" elif finish_reason == "tool_use": # anthropic return "tool_calls" - elif finish_reason == "content_filtered": - return "content_filter" + elif finish_reason == "compaction": + return "length" return finish_reason diff --git a/litellm/litellm_core_utils/initialize_dynamic_callback_params.py b/litellm/litellm_core_utils/initialize_dynamic_callback_params.py index c425319b4d4..ff521d47804 100644 --- a/litellm/litellm_core_utils/initialize_dynamic_callback_params.py +++ b/litellm/litellm_core_utils/initialize_dynamic_callback_params.py @@ -1,8 +1,35 @@ from typing import Dict, Optional - from litellm.secret_managers.main import get_secret_str from litellm.types.utils import StandardCallbackDynamicParams +# Hardcoded list of supported callback params to avoid runtime inspection issues with TypedDict +_supported_callback_params = [ + "langfuse_public_key", + "langfuse_secret", + "langfuse_secret_key", + "langfuse_host", + "langfuse_prompt_version", + "gcs_bucket_name", + "gcs_path_service_account", + "langsmith_api_key", + "langsmith_project", + "langsmith_base_url", + "langsmith_sampling_rate", + "langsmith_tenant_id", + "humanloop_api_key", + "arize_api_key", + "arize_space_key", + "arize_space_id", + "posthog_api_key", + "posthog_host", + "braintrust_api_key", + "braintrust_project", + "braintrust_host", + "slack_webhook_url", + "lunary_public_key", + "turn_off_message_logging", +] + def initialize_standard_callback_dynamic_params( kwargs: Optional[Dict] = None, @@ -15,13 +42,10 @@ def initialize_standard_callback_dynamic_params( standard_callback_dynamic_params = StandardCallbackDynamicParams() if kwargs: - _supported_callback_params = ( - StandardCallbackDynamicParams.__annotations__.keys() - ) - + # 1. Check top-level kwargs for param in _supported_callback_params: if param in kwargs: - _param_value = kwargs.pop(param) + _param_value = kwargs.get(param) if ( _param_value is not None and isinstance(_param_value, str) @@ -30,4 +54,22 @@ def initialize_standard_callback_dynamic_params( _param_value = get_secret_str(secret_name=_param_value) standard_callback_dynamic_params[param] = _param_value # type: ignore + # 2. Fallback: check "metadata" or "litellm_params" -> "metadata" + metadata = (kwargs.get("metadata") or {}).copy() + litellm_params = kwargs.get("litellm_params") or {} + if isinstance(litellm_params, dict): + metadata.update(litellm_params.get("metadata") or {}) + + if isinstance(metadata, dict): + for param in _supported_callback_params: + if param not in standard_callback_dynamic_params and param in metadata: + _param_value = metadata.get(param) + if ( + _param_value is not None + and isinstance(_param_value, str) + and "os.environ/" in _param_value + ): + _param_value = get_secret_str(secret_name=_param_value) + standard_callback_dynamic_params[param] = _param_value # type: ignore + return standard_callback_dynamic_params diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index 4ad2d1002bc..14015225f38 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -2435,6 +2435,36 @@ async def async_success_handler( # noqa: PLR0915 standard_built_in_tools_params=self.standard_built_in_tools_params, ) + # print standard logging payload + if ( + standard_logging_payload := self.model_call_details.get( + "standard_logging_object" + ) + ) is not None: + emit_standard_logging_payload(standard_logging_payload) + elif self.call_type == "pass_through_endpoint": + print_verbose( + "Async success callbacks: Got a pass-through endpoint response" + ) + + self.model_call_details["async_complete_streaming_response"] = result + + # cost calculation not possible for pass-through + self.model_call_details["response_cost"] = None + + ## STANDARDIZED LOGGING PAYLOAD + self.model_call_details[ + "standard_logging_object" + ] = get_standard_logging_object_payload( + kwargs=self.model_call_details, + init_response_obj=result, + start_time=start_time, + end_time=end_time, + logging_obj=self, + status="success", + standard_built_in_tools_params=self.standard_built_in_tools_params, + ) + # print standard logging payload if ( standard_logging_payload := self.model_call_details.get( @@ -3887,18 +3917,6 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 return langfuse_logger # type: ignore elif logging_integration == "langfuse_otel": from litellm.integrations.langfuse.langfuse_otel import LangfuseOtelLogger - from litellm.integrations.opentelemetry import ( - OpenTelemetry, - OpenTelemetryConfig, - ) - - langfuse_otel_config = LangfuseOtelLogger.get_langfuse_otel_config() - - # The endpoint and headers are now set as environment variables by get_langfuse_otel_config() - otel_config = OpenTelemetryConfig( - exporter=langfuse_otel_config.protocol, - headers=langfuse_otel_config.otlp_auth_headers, - ) for callback in _in_memory_loggers: if ( @@ -3906,8 +3924,10 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 and callback.callback_name == "langfuse_otel" ): return callback # type: ignore + # Allow LangfuseOtelLogger to initialize its own config safely + # This prevents startup crashes if LANGFUSE keys are not in env (e.g. for dynamic usage) _otel_logger = LangfuseOtelLogger( - config=otel_config, callback_name="langfuse_otel" + config=None, callback_name="langfuse_otel" ) _in_memory_loggers.append(_otel_logger) return _otel_logger # type: ignore diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py index fe06641a389..2308dc7beca 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/utils.py +++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py @@ -215,6 +215,9 @@ def _get_token_base_cost( cache_creation_tiered_key = ( f"cache_creation_input_token_cost_above_{threshold_str}_tokens" ) + cache_creation_1hr_tiered_key = ( + f"cache_creation_input_token_cost_above_1hr_above_{threshold_str}_tokens" + ) cache_read_tiered_key = ( f"cache_read_input_token_cost_above_{threshold_str}_tokens" ) @@ -229,6 +232,16 @@ def _get_token_base_cost( ), ) + if cache_creation_1hr_tiered_key in model_info: + cache_creation_cost_above_1hr = cast( + float, + _get_cost_per_unit( + model_info, + cache_creation_1hr_tiered_key, + cache_creation_cost_above_1hr, + ), + ) + if cache_read_tiered_key in model_info: cache_read_cost = cast( float, diff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.py index 4f76a5bad03..435ae078a65 100644 --- a/litellm/litellm_core_utils/logging_callback_manager.py +++ b/litellm/litellm_core_utils/logging_callback_manager.py @@ -114,6 +114,27 @@ def remove_callback_from_list_by_object( for c in remove_list: callback_list.remove(c) + def remove_callbacks_by_type(self, callback_list, callback_type): + """ + Remove all callbacks of a specific type from a callback list. + + Args: + callback_list: The list to remove callbacks from (e.g., litellm.callbacks) + callback_type: The class type to match (e.g., SemanticToolFilterHook) + + Example: + litellm.logging_callback_manager.remove_callbacks_by_type( + litellm.callbacks, SemanticToolFilterHook + ) + """ + if not isinstance(callback_list, list): + return + + remove_list = [c for c in callback_list if isinstance(c, callback_type)] + + for c in remove_list: + callback_list.remove(c) + def _add_string_callback_to_list( self, callback: str, parent_list: List[Union[CustomLogger, Callable, str]] ): diff --git a/litellm/litellm_core_utils/model_param_helper.py b/litellm/litellm_core_utils/model_param_helper.py index 91f2f1341cf..4d45c47c224 100644 --- a/litellm/litellm_core_utils/model_param_helper.py +++ b/litellm/litellm_core_utils/model_param_helper.py @@ -17,15 +17,16 @@ class ModelParamHelper: + # Cached at class level — deterministic set built from static OpenAI type annotations + _relevant_logging_args: frozenset = frozenset() + @staticmethod def get_standard_logging_model_parameters( model_parameters: dict, ) -> dict: """ """ standard_logging_model_parameters: dict = {} - supported_model_parameters = ( - ModelParamHelper._get_relevant_args_to_use_for_logging() - ) + supported_model_parameters = ModelParamHelper._relevant_logging_args for key, value in model_parameters.items(): if key in supported_model_parameters: @@ -172,3 +173,8 @@ def _get_exclude_kwargs() -> Set[str]: Get the kwargs to exclude from the cache key """ return set(["metadata"]) + + +ModelParamHelper._relevant_logging_args = frozenset( + ModelParamHelper._get_relevant_args_to_use_for_logging() +) diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py index 7790fb83361..b1c2d0a52f5 100644 --- a/litellm/litellm_core_utils/prompt_templates/common_utils.py +++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py @@ -443,13 +443,21 @@ def update_messages_with_model_file_ids( def update_responses_input_with_model_file_ids( input: Any, + model_id: Optional[str] = None, + model_file_id_mapping: Optional[Dict[str, Dict[str, str]]] = None, ) -> Union[str, List[Dict[str, Any]]]: """ Updates responses API input with provider-specific file IDs. File IDs are always inside the content array, not as direct input_file items. - For managed files (unified file IDs), decodes the base64-encoded unified file ID - and extracts the llm_output_file_id directly. + For managed files (unified file IDs), uses model_file_id_mapping if provided, + otherwise decodes the base64-encoded unified file ID and extracts the llm_output_file_id directly. + + Args: + input: The responses API input parameter + model_id: The model ID to use for looking up provider-specific file IDs + model_file_id_mapping: Dictionary mapping litellm file IDs to provider file IDs + Format: {"litellm_file_id": {"model_id": "provider_file_id"}} """ from litellm.proxy.openai_files_endpoints.common_utils import ( _is_base64_encoded_unified_file_id, @@ -479,22 +487,35 @@ def update_responses_input_with_model_file_ids( ): file_id = content_item.get("file_id") if file_id: - # Check if this is a managed file ID (base64-encoded unified file ID) - is_unified_file_id = _is_base64_encoded_unified_file_id(file_id) - if is_unified_file_id: - unified_file_id = convert_b64_uid_to_unified_uid(file_id) - if "llm_output_file_id," in unified_file_id: - provider_file_id = unified_file_id.split( - "llm_output_file_id," - )[1].split(";")[0] - else: - # Fallback: keep original if we can't extract - provider_file_id = file_id + provider_file_id = file_id # Default to original + + # Check if we have a mapping for this file ID + if model_file_id_mapping and model_id and file_id in model_file_id_mapping: + # Use the model-specific file ID from mapping + provider_file_id = ( + model_file_id_mapping.get(file_id, {}).get(model_id) + or file_id + ) updated_content_item = content_item.copy() updated_content_item["file_id"] = provider_file_id updated_content.append(updated_content_item) else: - updated_content.append(content_item) + # Check if this is a base64-encoded unified file ID without mapping + is_unified_file_id = _is_base64_encoded_unified_file_id(file_id) + if is_unified_file_id: + # Fallback: decode unified file ID + unified_file_id = convert_b64_uid_to_unified_uid(file_id) + if "llm_output_file_id," in unified_file_id: + provider_file_id = unified_file_id.split( + "llm_output_file_id," + )[1].split(";")[0] + + updated_content_item = content_item.copy() + updated_content_item["file_id"] = provider_file_id + updated_content.append(updated_content_item) + else: + # Not a managed file, keep as-is + updated_content.append(content_item) else: updated_content.append(content_item) else: @@ -506,6 +527,68 @@ def update_responses_input_with_model_file_ids( return updated_input +def update_responses_tools_with_model_file_ids( + tools: Optional[List[Dict[str, Any]]], + model_id: Optional[str] = None, + model_file_id_mapping: Optional[Dict[str, Dict[str, str]]] = None, +) -> Optional[List[Dict[str, Any]]]: + """ + Updates responses API tools with provider-specific file IDs. + + Handles code_interpreter tools with container.file_ids. + + Args: + tools: The responses API tools parameter + model_id: The model ID to use for looking up provider-specific file IDs + model_file_id_mapping: Dictionary mapping litellm file IDs to provider file IDs + Format: {"litellm_file_id": {"model_id": "provider_file_id"}} + """ + if not tools or not isinstance(tools, list): + return tools + + if not model_file_id_mapping or not model_id: + return tools + + updated_tools = [] + for tool in tools: + if not isinstance(tool, dict): + updated_tools.append(tool) + continue + + updated_tool = tool.copy() + + # Handle code_interpreter with container file_ids + if tool.get("type") == "code_interpreter": + container = tool.get("container") + if isinstance(container, dict): + container_file_ids = container.get("file_ids") + if isinstance(container_file_ids, list): + updated_file_ids = [] + for file_id in container_file_ids: + if isinstance(file_id, str): + # Check if we have a mapping for this file ID + if file_id in model_file_id_mapping: + # Map to provider-specific file ID + provider_file_id = ( + model_file_id_mapping.get(file_id, {}).get(model_id) + or file_id + ) + updated_file_ids.append(provider_file_id) + else: + updated_file_ids.append(file_id) + else: + updated_file_ids.append(file_id) + + # Update the tool with new file IDs + updated_container = container.copy() + updated_container["file_ids"] = updated_file_ids + updated_tool["container"] = updated_container + + updated_tools.append(updated_tool) + + return updated_tools + + def extract_file_data(file_data: FileTypes) -> ExtractedFileData: """ Extracts and processes file data from various input formats. diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py index 0e1637a65ba..f9ecd78ff1c 100644 --- a/litellm/litellm_core_utils/prompt_templates/factory.py +++ b/litellm/litellm_core_utils/prompt_templates/factory.py @@ -2190,6 +2190,16 @@ def anthropic_messages_pt( # noqa: PLR0915 while msg_i < len(messages) and messages[msg_i]["role"] == "assistant": assistant_content_block: ChatCompletionAssistantMessage = messages[msg_i] # type: ignore + # Extract compaction_blocks from provider_specific_fields and add them first + _provider_specific_fields_raw = assistant_content_block.get( + "provider_specific_fields" + ) + if isinstance(_provider_specific_fields_raw, dict): + _compaction_blocks = _provider_specific_fields_raw.get("compaction_blocks") + if _compaction_blocks and isinstance(_compaction_blocks, list): + # Add compaction blocks at the beginning of assistant content : https://platform.claude.com/docs/en/build-with-claude/compaction + assistant_content.extend(_compaction_blocks) # type: ignore + thinking_blocks = assistant_content_block.get("thinking_blocks", None) if ( thinking_blocks is not None @@ -3399,6 +3409,59 @@ def _convert_to_bedrock_tool_call_result( return content_block +def _deduplicate_bedrock_content_blocks( + blocks: List[BedrockContentBlock], + block_key: str, + id_key: str = "toolUseId", +) -> List[BedrockContentBlock]: + """ + Remove duplicate content blocks that share the same ID under ``block_key``. + + Bedrock requires all toolResult and toolUse IDs within a single message to + be unique. When merging consecutive messages, duplicates can occur if the + same tool_call_id appears multiple times in conversation history. + + When duplicates exist, the first occurrence is retained and subsequent ones + are discarded. A warning is logged for every dropped block so that + upstream duplication bugs remain visible. + + Blocks that do not contain ``block_key`` (e.g., cachePoint, text) are + always preserved. + + Args: + blocks: The list of Bedrock content blocks to deduplicate. + block_key: The dict key to inspect (e.g. ``"toolResult"`` or ``"toolUse"``). + id_key: The nested key that holds the unique ID (default ``"toolUseId"``). + """ + seen_ids: Set[str] = set() + deduplicated: List[BedrockContentBlock] = [] + for block in blocks: + keyed = block.get(block_key) + if keyed is not None and isinstance(keyed, dict): + block_id = keyed.get(id_key) + if block_id: + if block_id in seen_ids: + verbose_logger.warning( + "Bedrock Converse: dropping duplicate %s block with " + "%s=%s. This may indicate duplicate tool messages in " + "conversation history.", + block_key, + id_key, + block_id, + ) + continue + seen_ids.add(block_id) + deduplicated.append(block) + return deduplicated + + +def _deduplicate_bedrock_tool_content( + tool_content: List[BedrockContentBlock], +) -> List[BedrockContentBlock]: + """Convenience wrapper: deduplicate ``toolResult`` blocks by ``toolUseId``.""" + return _deduplicate_bedrock_content_blocks(tool_content, "toolResult") + + def _insert_assistant_continue_message( messages: List[BedrockMessageBlock], assistant_continue_message: Optional[ @@ -3867,6 +3930,8 @@ async def _bedrock_converse_messages_pt_async( # noqa: PLR0915 tool_content.append(cache_point_block) msg_i += 1 + # Deduplicate toolResult blocks with the same toolUseId + tool_content = _deduplicate_bedrock_tool_content(tool_content) if tool_content: # if last message was a 'user' message, then add a blank assistant message (bedrock requires alternating roles) if len(contents) > 0 and contents[-1]["role"] == "user": @@ -3932,10 +3997,12 @@ async def _bedrock_converse_messages_pt_async( # noqa: PLR0915 assistant_parts=assistants_parts, ) elif element["type"] == "text": - assistants_part = BedrockContentBlock( - text=element["text"] - ) - assistants_parts.append(assistants_part) + # Skip completely empty strings to avoid blank content blocks + if element.get("text", "").strip(): + assistants_part = BedrockContentBlock( + text=element["text"] + ) + assistants_parts.append(assistants_part) elif element["type"] == "image_url": if isinstance(element["image_url"], dict): image_url = element["image_url"]["url"] @@ -3960,9 +4027,12 @@ async def _bedrock_converse_messages_pt_async( # noqa: PLR0915 elif _assistant_content is not None and isinstance( _assistant_content, str ): - assistant_content.append( - BedrockContentBlock(text=_assistant_content) - ) + # Skip completely empty strings to avoid blank content blocks + if _assistant_content.strip(): + assistant_content.append( + BedrockContentBlock(text=_assistant_content) + ) + # If content is empty/whitespace, skip it (don't add a placeholder) # Add cache point block for assistant string content _cache_point_block = ( litellm.AmazonConverseConfig()._get_cache_point_block( @@ -3980,6 +4050,8 @@ async def _bedrock_converse_messages_pt_async( # noqa: PLR0915 msg_i += 1 + assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse") + if assistant_content: contents.append( BedrockMessageBlock(role="assistant", content=assistant_content) @@ -4230,6 +4302,8 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 tool_content.append(cache_point_block) msg_i += 1 + # Deduplicate toolResult blocks with the same toolUseId + tool_content = _deduplicate_bedrock_tool_content(tool_content) if tool_content: # if last message was a 'user' message, then add a blank assistant message (bedrock requires alternating roles) if len(contents) > 0 and contents[-1]["role"] == "user": @@ -4289,12 +4363,11 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 assistant_parts=assistants_parts, ) elif element["type"] == "text": - # AWS Bedrock doesn't allow empty or whitespace-only text content, so use placeholder for empty strings - text_content = ( - element["text"] if element["text"].strip() else "." - ) - assistants_part = BedrockContentBlock(text=text_content) - assistants_parts.append(assistants_part) + # AWS Bedrock doesn't allow empty or whitespace-only text content + # Skip completely empty strings to avoid blank content blocks + if element.get("text", "").strip(): + assistants_part = BedrockContentBlock(text=element["text"]) + assistants_parts.append(assistants_part) elif element["type"] == "image_url": if isinstance(element["image_url"], dict): image_url = element["image_url"]["url"] @@ -4317,9 +4390,9 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 assistants_parts.append(_cache_point_block) assistant_content.extend(assistants_parts) elif _assistant_content is not None and isinstance(_assistant_content, str): - # AWS Bedrock doesn't allow empty or whitespace-only text content, so use placeholder for empty strings - text_content = _assistant_content if _assistant_content.strip() else "." - assistant_content.append(BedrockContentBlock(text=text_content)) + # Skip completely empty strings to avoid blank content blocks + if _assistant_content.strip(): + assistant_content.append(BedrockContentBlock(text=_assistant_content)) # Add cache point block for assistant string content _cache_point_block = ( litellm.AmazonConverseConfig()._get_cache_point_block( @@ -4336,6 +4409,8 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 msg_i += 1 + assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse") + if assistant_content: contents.append( BedrockMessageBlock(role="assistant", content=assistant_content) diff --git a/litellm/litellm_core_utils/redact_messages.py b/litellm/litellm_core_utils/redact_messages.py index 0effed3db70..aa763dc9899 100644 --- a/litellm/litellm_core_utils/redact_messages.py +++ b/litellm/litellm_core_utils/redact_messages.py @@ -130,6 +130,11 @@ def perform_redaction(model_call_details: dict, result): def should_redact_message_logging(model_call_details: dict) -> bool: """ Determine if message logging should be redacted. + + Priority order: + 1. Dynamic parameter (turn_off_message_logging in request) + 2. Headers (litellm-disable-message-redaction / litellm-enable-message-redaction) + 3. Global setting (litellm.turn_off_message_logging) """ litellm_params = model_call_details.get("litellm_params", {}) @@ -139,36 +144,36 @@ def should_redact_message_logging(model_call_details: dict) -> bool: # Get headers from the metadata request_headers = metadata.get("headers", {}) if isinstance(metadata, dict) else {} - possible_request_headers = [ + # Check for headers that explicitly control redaction + if request_headers and bool( + request_headers.get("litellm-disable-message-redaction", False) + ): + # User explicitly disabled redaction via header + return False + + possible_enable_headers = [ "litellm-enable-message-redaction", # old header. maintain backwards compatibility "x-litellm-enable-message-redaction", # new header ] is_redaction_enabled_via_header = False - for header in possible_request_headers: + for header in possible_enable_headers: if bool(request_headers.get(header, False)): is_redaction_enabled_via_header = True break - # check if user opted out of logging message/response to callbacks - if ( - litellm.turn_off_message_logging is not True - and is_redaction_enabled_via_header is not True - and _get_turn_off_message_logging_from_dynamic_params(model_call_details) - is not True - ): - return False - - if request_headers and bool( - request_headers.get("litellm-disable-message-redaction", False) - ): - return False - - # user has OPTED OUT of message redaction - if _get_turn_off_message_logging_from_dynamic_params(model_call_details) is False: - return False - - return True + # Priority 1: Check dynamic parameter first (if explicitly set) + dynamic_turn_off = _get_turn_off_message_logging_from_dynamic_params(model_call_details) + if dynamic_turn_off is not None: + # Dynamic parameter is explicitly set, use it + return dynamic_turn_off + + # Priority 2: Check if header explicitly enables redaction + if is_redaction_enabled_via_header: + return True + + # Priority 3: Fall back to global setting + return litellm.turn_off_message_logging is True def redact_message_input_output_from_logging( diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py index a99bd1cd0f3..6b9e51034c0 100644 --- a/litellm/litellm_core_utils/token_counter.py +++ b/litellm/litellm_core_utils/token_counter.py @@ -706,7 +706,7 @@ def _count_content_list( if isinstance(c, str): num_tokens += count_function(c) elif c["type"] == "text": - num_tokens += count_function(c.get("text", "")) + num_tokens += count_function(str(c.get("text", ""))) elif c["type"] == "image_url": image_url = c.get("image_url") num_tokens += _count_image_tokens( @@ -722,7 +722,7 @@ def _count_content_list( elif c["type"] == "thinking": # Claude extended thinking content block # Count the thinking text and skip signature (opaque signature blob) - thinking_text = c.get("thinking", "") + thinking_text = str(c.get("thinking", "")) if thinking_text: num_tokens += count_function(thinking_text) else: diff --git a/litellm/llms/a2a/__init__.py b/litellm/llms/a2a/__init__.py new file mode 100644 index 00000000000..043efa5e8bf --- /dev/null +++ b/litellm/llms/a2a/__init__.py @@ -0,0 +1,6 @@ +""" +A2A (Agent-to-Agent) Protocol Provider for LiteLLM +""" +from .chat.transformation import A2AConfig + +__all__ = ["A2AConfig"] diff --git a/litellm/llms/a2a/chat/__init__.py b/litellm/llms/a2a/chat/__init__.py new file mode 100644 index 00000000000..76bf4dd71d9 --- /dev/null +++ b/litellm/llms/a2a/chat/__init__.py @@ -0,0 +1,6 @@ +""" +A2A Chat Completion Implementation +""" +from .transformation import A2AConfig + +__all__ = ["A2AConfig"] diff --git a/litellm/llms/a2a/chat/guardrail_translation/README.md b/litellm/llms/a2a/chat/guardrail_translation/README.md new file mode 100644 index 00000000000..1e18f5cda3a --- /dev/null +++ b/litellm/llms/a2a/chat/guardrail_translation/README.md @@ -0,0 +1,155 @@ +# A2A Protocol Guardrail Translation Handler + +Handler for processing A2A (Agent-to-Agent) Protocol messages with guardrails. + +## Overview + +This handler processes A2A JSON-RPC 2.0 input/output by: +1. Extracting text from message parts (`kind: "text"`) +2. Applying guardrails to text content +3. Mapping guardrailed text back to original structure + +## A2A Protocol Format + +### Input Format (JSON-RPC 2.0) + +```json +{ + "jsonrpc": "2.0", + "id": "request-id", + "method": "message/send", + "params": { + "message": { + "kind": "message", + "messageId": "...", + "role": "user", + "parts": [ + {"kind": "text", "text": "Hello, my SSN is 123-45-6789"} + ] + }, + "metadata": { + "guardrails": ["block-ssn"] + } + } +} +``` + +### Output Formats + +The handler supports multiple A2A response formats: + +**Direct message:** +```json +{ + "result": { + "kind": "message", + "parts": [{"kind": "text", "text": "Response text"}] + } +} +``` + +**Nested message:** +```json +{ + "result": { + "message": { + "parts": [{"kind": "text", "text": "Response text"}] + } + } +} +``` + +**Task with artifacts:** +```json +{ + "result": { + "kind": "task", + "artifacts": [ + {"parts": [{"kind": "text", "text": "Artifact text"}]} + ] + } +} +``` + +**Task with status message:** +```json +{ + "result": { + "kind": "task", + "status": { + "message": { + "parts": [{"kind": "text", "text": "Status message"}] + } + } + } +} +``` + +**Streaming artifact-update:** +```json +{ + "result": { + "kind": "artifact-update", + "artifact": { + "parts": [{"kind": "text", "text": "Streaming text"}] + } + } +} +``` + +## Usage + +The handler is automatically discovered and applied when guardrails are used with A2A endpoints. + +### Via LiteLLM Proxy + +```bash +curl -X POST 'http://localhost:4000/a2a/my-agent' \ +-H 'Content-Type: application/json' \ +-H 'Authorization: Bearer your-api-key' \ +-d '{ + "jsonrpc": "2.0", + "id": "1", + "method": "message/send", + "params": { + "message": { + "kind": "message", + "messageId": "msg-1", + "role": "user", + "parts": [{"kind": "text", "text": "Hello, my SSN is 123-45-6789"}] + }, + "metadata": { + "guardrails": ["block-ssn"] + } + } +}' +``` + +### Specifying Guardrails + +Guardrails can be specified in the A2A request via the `metadata.guardrails` field: + +```json +{ + "params": { + "message": {...}, + "metadata": { + "guardrails": ["block-ssn", "pii-filter"] + } + } +} +``` + +## Extension + +Override these methods to customize behavior: + +- `_extract_texts_from_result()`: Custom text extraction from A2A responses +- `_extract_texts_from_parts()`: Custom text extraction from message parts +- `_apply_text_to_path()`: Custom application of guardrailed text + +## Call Types + +This handler is registered for: +- `CallTypes.send_message`: Synchronous A2A message sending +- `CallTypes.asend_message`: Asynchronous A2A message sending diff --git a/litellm/llms/a2a/chat/guardrail_translation/__init__.py b/litellm/llms/a2a/chat/guardrail_translation/__init__.py new file mode 100644 index 00000000000..13c20677485 --- /dev/null +++ b/litellm/llms/a2a/chat/guardrail_translation/__init__.py @@ -0,0 +1,11 @@ +"""A2A Protocol handler for Unified Guardrails.""" + +from litellm.llms.a2a.chat.guardrail_translation.handler import A2AGuardrailHandler +from litellm.types.utils import CallTypes + +guardrail_translation_mappings = { + CallTypes.send_message: A2AGuardrailHandler, + CallTypes.asend_message: A2AGuardrailHandler, +} + +__all__ = ["guardrail_translation_mappings"] diff --git a/litellm/llms/a2a/chat/guardrail_translation/handler.py b/litellm/llms/a2a/chat/guardrail_translation/handler.py new file mode 100644 index 00000000000..770453f2def --- /dev/null +++ b/litellm/llms/a2a/chat/guardrail_translation/handler.py @@ -0,0 +1,315 @@ +""" +A2A Protocol Handler for Unified Guardrails + +This module provides guardrail translation support for A2A (Agent-to-Agent) Protocol. +It handles both JSON-RPC 2.0 input requests and output responses, extracting text +from message parts and applying guardrails. + +A2A Protocol Format: +- Input: JSON-RPC 2.0 with params.message.parts containing text parts +- Output: JSON-RPC 2.0 with result containing message/artifact parts +""" + +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union + +from litellm._logging import verbose_proxy_logger +from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation +from litellm.types.utils import GenericGuardrailAPIInputs + +if TYPE_CHECKING: + from litellm.integrations.custom_guardrail import CustomGuardrail + from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj + from litellm.proxy._types import UserAPIKeyAuth + + +class A2AGuardrailHandler(BaseTranslation): + """ + Handler for processing A2A Protocol messages with guardrails. + + This class provides methods to: + 1. Process input messages (pre-call hook) - extracts text from A2A message parts + 2. Process output responses (post-call hook) - extracts text from A2A response parts + + A2A Message Format: + - Input: params.message.parts[].text (where kind == "text") + - Output: result.message.parts[].text or result.artifacts[].parts[].text + """ + + async def process_input_messages( + self, + data: dict, + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None, + ) -> Any: + """ + Process A2A input messages by applying guardrails to text content. + + Extracts text from A2A message parts and applies guardrails. + + Args: + data: The A2A JSON-RPC 2.0 request data + guardrail_to_apply: The guardrail instance to apply + litellm_logging_obj: Optional logging object + + Returns: + Modified data with guardrails applied to text content + """ + # A2A request format: { "params": { "message": { "parts": [...] } } } + params = data.get("params", {}) + message = params.get("message", {}) + parts = message.get("parts", []) + + if not parts: + verbose_proxy_logger.debug("A2A: No parts in message, skipping guardrail") + return data + + texts_to_check: List[str] = [] + text_part_indices: List[int] = [] # Track which parts contain text + + # Step 1: Extract text from all text parts + for part_idx, part in enumerate(parts): + if part.get("kind") == "text": + text = part.get("text", "") + if text: + texts_to_check.append(text) + text_part_indices.append(part_idx) + + # Step 2: Apply guardrail to all texts in batch + if texts_to_check: + inputs = GenericGuardrailAPIInputs(texts=texts_to_check) + + # Pass the structured A2A message to guardrails + inputs["structured_messages"] = [message] + + # Include agent model info if available + model = data.get("model") + if model: + inputs["model"] = model + + guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + inputs=inputs, + request_data=data, + input_type="request", + logging_obj=litellm_logging_obj, + ) + + guardrailed_texts = guardrailed_inputs.get("texts", []) + + # Step 3: Apply guardrailed text back to original parts + if guardrailed_texts and len(guardrailed_texts) == len(text_part_indices): + for task_idx, part_idx in enumerate(text_part_indices): + parts[part_idx]["text"] = guardrailed_texts[task_idx] + + verbose_proxy_logger.debug("A2A: Processed input message: %s", message) + + return data + + async def process_output_response( + self, + response: Any, + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None, + user_api_key_dict: Optional["UserAPIKeyAuth"] = None, + ) -> Any: + """ + Process A2A output response by applying guardrails to text content. + + Handles multiple A2A response formats: + - Direct message: {"result": {"kind": "message", "parts": [...]}} + - Nested message: {"result": {"message": {"parts": [...]}}} + - Task with artifacts: {"result": {"kind": "task", "artifacts": [{"parts": [...]}]}} + - Task with status message: {"result": {"kind": "task", "status": {"message": {"parts": [...]}}}} + + Args: + response: A2A JSON-RPC 2.0 response dict or object + guardrail_to_apply: The guardrail instance to apply + litellm_logging_obj: Optional logging object + user_api_key_dict: User API key metadata + + Returns: + Modified response with guardrails applied to text content + """ + # Handle both dict and Pydantic model responses + if hasattr(response, "model_dump"): + response_dict = response.model_dump() + is_pydantic = True + elif isinstance(response, dict): + response_dict = response + is_pydantic = False + else: + verbose_proxy_logger.warning( + "A2A: Unknown response type %s, skipping guardrail", type(response) + ) + return response + + result = response_dict.get("result", {}) + if not result or not isinstance(result, dict): + verbose_proxy_logger.debug("A2A: No result in response, skipping guardrail") + return response + + # Find all text-containing parts in the response + texts_to_check: List[str] = [] + # Each mapping is (path_to_parts_list, part_index) + # path_to_parts_list is a tuple of keys to navigate to the parts list + task_mappings: List[Tuple[Tuple[str, ...], int]] = [] + + # Extract texts from all possible locations + self._extract_texts_from_result( + result=result, + texts_to_check=texts_to_check, + task_mappings=task_mappings, + ) + + if not texts_to_check: + verbose_proxy_logger.debug("A2A: No text content in response") + return response + + # Step 2: Apply guardrail to all texts in batch + # Create a request_data dict with response info and user API key metadata + request_data: dict = {"response": response_dict} + + # Add user API key metadata with prefixed keys + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) + if user_metadata: + request_data["litellm_metadata"] = user_metadata + + inputs = GenericGuardrailAPIInputs(texts=texts_to_check) + + guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=litellm_logging_obj, + ) + + guardrailed_texts = guardrailed_inputs.get("texts", []) + + # Step 3: Apply guardrailed text back to original response + if guardrailed_texts and len(guardrailed_texts) == len(task_mappings): + for task_idx, (path, part_idx) in enumerate(task_mappings): + self._apply_text_to_path( + result=result, + path=path, + part_idx=part_idx, + text=guardrailed_texts[task_idx], + ) + + verbose_proxy_logger.debug("A2A: Processed output response") + + # Update the original response + if is_pydantic: + # For Pydantic models, we need to update the underlying dict + # and the model will reflect the changes + response_dict["result"] = result + return response + else: + response["result"] = result + return response + + def _extract_texts_from_result( + self, + result: Dict[str, Any], + texts_to_check: List[str], + task_mappings: List[Tuple[Tuple[str, ...], int]], + ) -> None: + """ + Extract text from all possible locations in an A2A result. + + Handles multiple response formats: + 1. Direct message with parts: {"parts": [...]} + 2. Nested message: {"message": {"parts": [...]}} + 3. Task with artifacts: {"artifacts": [{"parts": [...]}]} + 4. Task with status message: {"status": {"message": {"parts": [...]}}} + 5. Streaming artifact-update: {"artifact": {"parts": [...]}} + """ + # Case 1: Direct parts in result (direct message) + if "parts" in result: + self._extract_texts_from_parts( + parts=result["parts"], + path=("parts",), + texts_to_check=texts_to_check, + task_mappings=task_mappings, + ) + + # Case 2: Nested message + message = result.get("message") + if message and isinstance(message, dict) and "parts" in message: + self._extract_texts_from_parts( + parts=message["parts"], + path=("message", "parts"), + texts_to_check=texts_to_check, + task_mappings=task_mappings, + ) + + # Case 3: Streaming artifact-update (singular artifact) + artifact = result.get("artifact") + if artifact and isinstance(artifact, dict) and "parts" in artifact: + self._extract_texts_from_parts( + parts=artifact["parts"], + path=("artifact", "parts"), + texts_to_check=texts_to_check, + task_mappings=task_mappings, + ) + + # Case 4: Task with status message + status = result.get("status", {}) + if isinstance(status, dict): + status_message = status.get("message") + if ( + status_message + and isinstance(status_message, dict) + and "parts" in status_message + ): + self._extract_texts_from_parts( + parts=status_message["parts"], + path=("status", "message", "parts"), + texts_to_check=texts_to_check, + task_mappings=task_mappings, + ) + + # Case 5: Task with artifacts (plural, array) + artifacts = result.get("artifacts", []) + if artifacts and isinstance(artifacts, list): + for artifact_idx, art in enumerate(artifacts): + if isinstance(art, dict) and "parts" in art: + self._extract_texts_from_parts( + parts=art["parts"], + path=("artifacts", str(artifact_idx), "parts"), + texts_to_check=texts_to_check, + task_mappings=task_mappings, + ) + + def _extract_texts_from_parts( + self, + parts: List[Dict[str, Any]], + path: Tuple[str, ...], + texts_to_check: List[str], + task_mappings: List[Tuple[Tuple[str, ...], int]], + ) -> None: + """Extract text from message parts.""" + for part_idx, part in enumerate(parts): + if part.get("kind") == "text": + text = part.get("text", "") + if text: + texts_to_check.append(text) + task_mappings.append((path, part_idx)) + + def _apply_text_to_path( + self, + result: Dict[Union[str, int], Any], + path: Tuple[str, ...], + part_idx: int, + text: str, + ) -> None: + """Apply guardrailed text back to the specified path in the result.""" + # Navigate to the parts list + current = result + for key in path: + if key.isdigit(): + # Array index + current = current[int(key)] + else: + current = current[key] + + # Update the text in the part + current[part_idx]["text"] = text diff --git a/litellm/llms/a2a/chat/streaming_iterator.py b/litellm/llms/a2a/chat/streaming_iterator.py new file mode 100644 index 00000000000..4b689414ddd --- /dev/null +++ b/litellm/llms/a2a/chat/streaming_iterator.py @@ -0,0 +1,103 @@ +""" +A2A Streaming Response Iterator +""" +from typing import Optional, Union + +from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator +from litellm.types.utils import GenericStreamingChunk, ModelResponseStream + +from ..common_utils import extract_text_from_a2a_response + + +class A2AModelResponseIterator(BaseModelResponseIterator): + """ + Iterator for parsing A2A streaming responses. + + Converts A2A JSON-RPC streaming chunks to OpenAI-compatible format. + """ + + def __init__( + self, + streaming_response, + sync_stream: bool, + json_mode: Optional[bool] = False, + model: str = "a2a/agent", + ): + super().__init__( + streaming_response=streaming_response, + sync_stream=sync_stream, + json_mode=json_mode, + ) + self.model = model + + def chunk_parser(self, chunk: dict) -> Union[GenericStreamingChunk, ModelResponseStream]: + """ + Parse A2A streaming chunk to OpenAI format. + + A2A chunk format: + { + "jsonrpc": "2.0", + "id": "request-id", + "result": { + "message": { + "parts": [{"kind": "text", "text": "content"}] + } + } + } + + Or for tasks: + { + "jsonrpc": "2.0", + "result": { + "kind": "task", + "status": {"state": "running"}, + "artifacts": [{"parts": [{"kind": "text", "text": "content"}]}] + } + } + """ + try: + # Extract text from A2A response + text = extract_text_from_a2a_response(chunk) + + # Determine finish reason + finish_reason = self._get_finish_reason(chunk) + + # Return generic streaming chunk + return GenericStreamingChunk( + text=text, + is_finished=bool(finish_reason), + finish_reason=finish_reason or "", + usage=None, + index=0, + tool_use=None, + ) + except Exception: + # Return empty chunk on parse error + return GenericStreamingChunk( + text="", + is_finished=False, + finish_reason="", + usage=None, + index=0, + tool_use=None, + ) + + def _get_finish_reason(self, chunk: dict) -> Optional[str]: + """Extract finish reason from A2A chunk""" + result = chunk.get("result", {}) + + # Check for task completion + if isinstance(result, dict): + status = result.get("status", {}) + if isinstance(status, dict): + state = status.get("state") + if state == "completed": + return "stop" + elif state == "failed": + return "stop" # Map failed state to 'stop' (valid finish_reason) + + # Check for [DONE] marker + if chunk.get("done") is True: + return "stop" + + return None diff --git a/litellm/llms/a2a/chat/transformation.py b/litellm/llms/a2a/chat/transformation.py new file mode 100644 index 00000000000..163cd5ab22e --- /dev/null +++ b/litellm/llms/a2a/chat/transformation.py @@ -0,0 +1,370 @@ +""" +A2A Protocol Transformation for LiteLLM +""" +import uuid +from typing import Any, Dict, Iterator, List, Optional, Union + +import httpx + +from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator +from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException +from litellm.types.llms.openai import AllMessageValues +from litellm.types.utils import Choices, Message, ModelResponse + +from ..common_utils import ( + A2AError, + convert_messages_to_prompt, + extract_text_from_a2a_response, +) +from .streaming_iterator import A2AModelResponseIterator + + +class A2AConfig(BaseConfig): + """ + Configuration for A2A (Agent-to-Agent) Protocol. + + Handles transformation between OpenAI and A2A JSON-RPC 2.0 formats. + """ + + @staticmethod + def resolve_agent_config_from_registry( + model: str, + api_base: Optional[str], + api_key: Optional[str], + headers: Optional[Dict[str, Any]], + optional_params: Dict[str, Any], + ) -> tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]: + """ + Resolve agent configuration from registry if model format is "a2a/". + + Extracts agent name from model string and looks up configuration in the + agent registry (if available in proxy context). + + Args: + model: Model string (e.g., "a2a/my-agent") + api_base: Explicit api_base (takes precedence over registry) + api_key: Explicit api_key (takes precedence over registry) + headers: Explicit headers (takes precedence over registry) + optional_params: Dict to merge additional litellm_params into + + Returns: + Tuple of (api_base, api_key, headers) with registry values filled in + """ + # Extract agent name from model (e.g., "a2a/my-agent" -> "my-agent") + agent_name = model.split("/", 1)[1] if "/" in model else None + + # Only lookup if agent name exists and some config is missing + if not agent_name or (api_base is not None and api_key is not None and headers is not None): + return api_base, api_key, headers + + # Try registry lookup (only available in proxy context) + try: + from litellm.proxy.agent_endpoints.agent_registry import ( + global_agent_registry, + ) + + agent = global_agent_registry.get_agent_by_name(agent_name) + if agent: + # Get api_base from agent card URL + if api_base is None and agent.agent_card_params: + api_base = agent.agent_card_params.get("url") + + # Get api_key, headers, and other params from litellm_params + if agent.litellm_params: + if api_key is None: + api_key = agent.litellm_params.get("api_key") + + if headers is None: + agent_headers = agent.litellm_params.get("headers") + if agent_headers: + headers = agent_headers + + # Merge other litellm_params (timeout, max_retries, etc.) + for key, value in agent.litellm_params.items(): + if key not in ["api_key", "api_base", "headers", "model"] and key not in optional_params: + optional_params[key] = value + except ImportError: + pass # Registry not available (not running in proxy context) + + return api_base, api_key, headers + + def get_supported_openai_params(self, model: str) -> List[str]: + """Return list of supported OpenAI parameters""" + return [ + "stream", + "temperature", + "max_tokens", + "top_p", + ] + + def map_openai_params( + self, + non_default_params: dict, + optional_params: dict, + model: str, + drop_params: bool, + ) -> dict: + """ + Map OpenAI parameters to A2A parameters. + + For A2A protocol, we need to map the stream parameter so + transform_request can determine which JSON-RPC method to use. + """ + # Map stream parameter + for param, value in non_default_params.items(): + if param == "stream" and value is True: + optional_params["stream"] = value + + return optional_params + + def validate_environment( + self, + headers: dict, + model: str, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> dict: + """ + Validate environment and set headers for A2A requests. + + Args: + headers: Request headers dict + model: Model name + messages: Messages list + optional_params: Optional parameters + litellm_params: LiteLLM parameters + api_key: API key (optional for A2A) + api_base: API base URL + + Returns: + Updated headers dict + """ + # Ensure Content-Type is set to application/json for JSON-RPC 2.0 + if "content-type" not in headers and "Content-Type" not in headers: + headers["Content-Type"] = "application/json" + + # Add Authorization header if API key is provided + if api_key is not None: + headers["Authorization"] = f"Bearer {api_key}" + + return headers + + 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 complete A2A agent endpoint URL. + + A2A agents use JSON-RPC 2.0 at the base URL, not specific paths. + The method (message/send or message/stream) is specified in the + JSON-RPC request body, not in the URL. + + Args: + api_base: Base URL of the A2A agent (e.g., "http://0.0.0.0:9999") + api_key: API key (not used for URL construction) + model: Model name (not used for A2A, agent determined by api_base) + optional_params: Optional parameters + litellm_params: LiteLLM parameters + stream: Whether this is a streaming request (affects JSON-RPC method) + + Returns: + Complete URL for the A2A endpoint (base URL) + """ + if api_base is None: + raise ValueError("api_base is required for A2A provider") + + # A2A uses JSON-RPC 2.0 at the base URL + # Remove trailing slash for consistency + return api_base.rstrip("/") + + def transform_request( + self, + model: str, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + headers: dict, + ) -> dict: + """ + Transform OpenAI request to A2A JSON-RPC 2.0 format. + + Args: + model: Model name + messages: List of OpenAI messages + optional_params: Optional parameters + litellm_params: LiteLLM parameters + headers: Request headers + + Returns: + A2A JSON-RPC 2.0 request dict + """ + # Generate request ID + request_id = str(uuid.uuid4()) + + if not messages: + raise ValueError("At least one message is required for A2A completion") + + # Convert all messages to maintain conversation history + # Use helper to format conversation with role prefixes + full_context = convert_messages_to_prompt(messages) + + # Create single A2A message with full conversation context + a2a_message = { + "role": "user", + "parts": [{"kind": "text", "text": full_context}], + "messageId": str(uuid.uuid4()), + } + + # Build JSON-RPC 2.0 request + # For A2A protocol, the method is "message/send" for non-streaming + # and "message/stream" for streaming + stream = optional_params.get("stream", False) + method = "message/stream" if stream else "message/send" + + request_data = { + "jsonrpc": "2.0", + "id": request_id, + "method": method, + "params": { + "message": a2a_message + } + } + + return request_data + + def transform_response( + self, + model: str, + raw_response: httpx.Response, + model_response: ModelResponse, + logging_obj: Any, + request_data: dict, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + encoding: Any, + api_key: Optional[str] = None, + json_mode: Optional[bool] = None, + ) -> ModelResponse: + """ + Transform A2A JSON-RPC 2.0 response to OpenAI format. + + Args: + model: Model name + raw_response: HTTP response from A2A agent + model_response: Model response object to populate + logging_obj: Logging object + request_data: Original request data + messages: Original messages + optional_params: Optional parameters + litellm_params: LiteLLM parameters + encoding: Encoding object + api_key: API key + json_mode: JSON mode flag + + Returns: + Populated ModelResponse object + """ + try: + response_json = raw_response.json() + except Exception as e: + raise A2AError( + status_code=raw_response.status_code, + message=f"Failed to parse A2A response: {str(e)}", + headers=dict(raw_response.headers), + ) + + # Check for JSON-RPC error + if "error" in response_json: + error = response_json["error"] + raise A2AError( + status_code=raw_response.status_code, + message=f"A2A error: {error.get('message', 'Unknown error')}", + headers=dict(raw_response.headers), + ) + + # Extract text from A2A response + text = extract_text_from_a2a_response(response_json) + + # Populate model response + model_response.choices = [ + Choices( + finish_reason="stop", + index=0, + message=Message( + content=text, + role="assistant", + ), + ) + ] + + # Set model + model_response.model = model + + # Set ID from response + model_response.id = response_json.get("id", str(uuid.uuid4())) + + return model_response + + def get_model_response_iterator( + self, + streaming_response: Union[Iterator, Any], + sync_stream: bool, + json_mode: Optional[bool] = False, + ) -> BaseModelResponseIterator: + """ + Get streaming iterator for A2A responses. + + Args: + streaming_response: Streaming response iterator + sync_stream: Whether this is a sync stream + json_mode: JSON mode flag + + Returns: + A2A streaming iterator + """ + return A2AModelResponseIterator( + streaming_response=streaming_response, + sync_stream=sync_stream, + json_mode=json_mode, + ) + + def _openai_message_to_a2a_message(self, message: Dict[str, Any]) -> Dict[str, Any]: + """ + Convert OpenAI message to A2A message format. + + Args: + message: OpenAI message dict + + Returns: + A2A message dict + """ + content = message.get("content", "") + role = message.get("role", "user") + + return { + "role": role, + "parts": [{"kind": "text", "text": str(content)}], + "messageId": str(uuid.uuid4()), + } + + def get_error_class( + self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] + ) -> BaseLLMException: + """Return appropriate error class for A2A errors""" + # Convert headers to dict if needed + headers_dict = dict(headers) if isinstance(headers, httpx.Headers) else headers + return A2AError( + status_code=status_code, + message=error_message, + headers=headers_dict, + ) diff --git a/litellm/llms/a2a/common_utils.py b/litellm/llms/a2a/common_utils.py new file mode 100644 index 00000000000..116e1205409 --- /dev/null +++ b/litellm/llms/a2a/common_utils.py @@ -0,0 +1,152 @@ +""" +Common utilities for A2A (Agent-to-Agent) Protocol +""" +from typing import Any, Dict, List + +from pydantic import BaseModel + +from litellm.litellm_core_utils.prompt_templates.common_utils import ( + convert_content_list_to_str, +) +from litellm.llms.base_llm.chat.transformation import BaseLLMException +from litellm.types.llms.openai import AllMessageValues + + +class A2AError(BaseLLMException): + """Base exception for A2A protocol errors""" + + def __init__( + self, + status_code: int, + message: str, + headers: Dict[str, Any] = {}, + ): + super().__init__( + status_code=status_code, + message=message, + headers=headers, + ) + + +def convert_messages_to_prompt(messages: List[AllMessageValues]) -> str: + """ + Convert OpenAI messages to a single prompt string for A2A agent. + + Formats each message as "{role}: {content}" and joins with newlines + to preserve conversation history. Handles both string and list content. + + Args: + messages: List of OpenAI-format messages + + Returns: + Formatted prompt string with full conversation context + """ + conversation_parts = [] + for msg in messages: + # Use LiteLLM's helper to extract text from content (handles both str and list) + content_text = convert_content_list_to_str(message=msg) + + # Get role + if isinstance(msg, BaseModel): + role = msg.model_dump().get("role", "user") + elif isinstance(msg, dict): + role = msg.get("role", "user") + else: + role = dict(msg).get("role", "user") # type: ignore + + if content_text: + conversation_parts.append(f"{role}: {content_text}") + + return "\n".join(conversation_parts) + + +def extract_text_from_a2a_message( + message: Dict[str, Any], depth: int = 0, max_depth: int = 10 +) -> str: + """ + Extract text content from A2A message parts. + + Args: + message: A2A message dict with 'parts' containing text parts + depth: Current recursion depth (internal use) + max_depth: Maximum recursion depth to prevent infinite loops + + Returns: + Concatenated text from all text parts + """ + if message is None or depth >= max_depth: + return "" + + parts = message.get("parts", []) + text_parts: List[str] = [] + + for part in parts: + if part.get("kind") == "text": + text_parts.append(part.get("text", "")) + # Handle nested parts if they exist + elif "parts" in part: + nested_text = extract_text_from_a2a_message(part, depth + 1, max_depth) + if nested_text: + text_parts.append(nested_text) + + return " ".join(text_parts) + + +def extract_text_from_a2a_response( + response_dict: Dict[str, Any], max_depth: int = 10 +) -> str: + """ + Extract text content from A2A response result. + + Args: + response_dict: A2A response dict with 'result' containing message + max_depth: Maximum recursion depth to prevent infinite loops + + Returns: + Text from response message parts + """ + result = response_dict.get("result", {}) + if not isinstance(result, dict): + return "" + + # A2A response can have different formats: + # 1. Direct message: {"result": {"kind": "message", "parts": [...]}} + # 2. Nested message: {"result": {"message": {"parts": [...]}}} + # 3. Task with artifacts: {"result": {"kind": "task", "artifacts": [{"parts": [...]}]}} + # 4. Task with status message: {"result": {"kind": "task", "status": {"message": {"parts": [...]}}}} + # 5. Streaming artifact-update: {"result": {"kind": "artifact-update", "artifact": {"parts": [...]}}} + + # Check if result itself has parts (direct message) + if "parts" in result: + return extract_text_from_a2a_message(result, depth=0, max_depth=max_depth) + + # Check for nested message + message = result.get("message") + if message: + return extract_text_from_a2a_message(message, depth=0, max_depth=max_depth) + + # Check for streaming artifact-update (singular artifact) + artifact = result.get("artifact") + if artifact and isinstance(artifact, dict): + return extract_text_from_a2a_message( + artifact, depth=0, max_depth=max_depth + ) + + # Check for task status message (common in Gemini A2A agents) + status = result.get("status", {}) + if isinstance(status, dict): + status_message = status.get("message") + if status_message: + return extract_text_from_a2a_message( + status_message, depth=0, max_depth=max_depth + ) + + # Handle task result with artifacts (plural, array) + artifacts = result.get("artifacts", []) + if artifacts and len(artifacts) > 0: + first_artifact = artifacts[0] + return extract_text_from_a2a_message( + first_artifact, depth=0, max_depth=max_depth + ) + + return "" diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py index 71d74121a30..a14e7d118e8 100644 --- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py +++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py @@ -34,6 +34,7 @@ ) from litellm.types.utils import ( ChatCompletionMessageToolCall, + Choices, GenericGuardrailAPIInputs, ModelResponse, ) @@ -74,9 +75,10 @@ async def process_input_messages( if messages is None: return data - chat_completion_compatible_request = ( + chat_completion_compatible_request, tool_name_mapping = ( LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( - anthropic_message_request=cast(AnthropicMessagesRequest, data) + # Use a shallow copy to avoid mutating request data (pop on litellm_metadata). + anthropic_message_request=cast(AnthropicMessagesRequest, data.copy()) ) ) @@ -84,9 +86,9 @@ async def process_input_messages( texts_to_check: List[str] = [] images_to_check: List[str] = [] - tools_to_check: List[ChatCompletionToolParam] = ( - chat_completion_compatible_request.get("tools", []) - ) + tools_to_check: List[ + ChatCompletionToolParam + ] = chat_completion_compatible_request.get("tools", []) task_mappings: List[Tuple[int, Optional[int]]] = [] # Track (message_index, content_index) for each text # content_index is None for string content, int for list content @@ -282,7 +284,10 @@ async def process_output_response( if hasattr(content_block, "model_dump"): block_dict = content_block.model_dump() else: - block_dict = {"type": block_type, "text": getattr(content_block, "text", None)} + block_dict = { + "type": block_type, + "text": getattr(content_block, "text", None), + } else: continue @@ -358,30 +363,40 @@ async def process_output_streaming_response( """ has_ended = self._check_streaming_has_ended(responses_so_far) if has_ended: - # build the model response from the responses_so_far - model_response = cast( - ModelResponse, - AnthropicPassthroughLoggingHandler._build_complete_streaming_response( - all_chunks=responses_so_far, - litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj), - model="", - ), - ) - tool_calls_list = cast(Optional[List[ChatCompletionMessageToolCall]], model_response.choices[0].message.tool_calls) # type: ignore - string_so_far = model_response.choices[0].message.content # type: ignore - guardrail_inputs = GenericGuardrailAPIInputs() - if string_so_far: - guardrail_inputs["texts"] = [string_so_far] - if tool_calls_list: - guardrail_inputs["tool_calls"] = tool_calls_list - - _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalid - inputs=guardrail_inputs, - request_data={}, - input_type="response", - logging_obj=litellm_logging_obj, + built_response = AnthropicPassthroughLoggingHandler._build_complete_streaming_response( + all_chunks=responses_so_far, + litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj), + model="", ) + + # Check if model_response is valid and has choices before accessing + if ( + built_response is not None + and hasattr(built_response, "choices") + and built_response.choices + ): + model_response = cast(ModelResponse, built_response) + first_choice = cast(Choices, model_response.choices[0]) + tool_calls_list = cast( + Optional[List[ChatCompletionMessageToolCall]], + first_choice.message.tool_calls, + ) + string_so_far = first_choice.message.content + guardrail_inputs = GenericGuardrailAPIInputs() + if string_so_far: + guardrail_inputs["texts"] = [string_so_far] + if tool_calls_list: + guardrail_inputs["tool_calls"] = tool_calls_list + + _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalid + inputs=guardrail_inputs, + request_data={}, + input_type="response", + logging_obj=litellm_logging_obj, + ) + else: + verbose_proxy_logger.debug("Skipping output guardrail - model response has no choices") return responses_so_far string_so_far = self.get_streaming_string_so_far(responses_so_far) @@ -648,7 +663,10 @@ async def _apply_guardrail_responses_to_output( if isinstance(content_block, dict): if content_block.get("type") == "text": cast(Dict[str, Any], content_block)["text"] = guardrail_response - elif hasattr(content_block, "type") and getattr(content_block, "type", None) == "text": + elif ( + hasattr(content_block, "type") + and getattr(content_block, "type", None) == "text" + ): # Update Pydantic object's text attribute if hasattr(content_block, "text"): content_block.text = guardrail_response diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.py index 6a9aafd076b..485e95d6489 100644 --- a/litellm/llms/anthropic/chat/handler.py +++ b/litellm/llms/anthropic/chat/handler.py @@ -512,6 +512,9 @@ def __init__( # Accumulate web_search_tool_result blocks for multi-turn reconstruction # See: https://github.com/BerriAI/litellm/issues/17737 self.web_search_results: List[Dict[str, Any]] = [] + + # Accumulate compaction blocks for multi-turn reconstruction + self.compaction_blocks: List[Dict[str, Any]] = [] def check_empty_tool_call_args(self) -> bool: """ @@ -592,6 +595,12 @@ def _content_block_delta_helper(self, chunk: dict) -> Tuple[ ) ] provider_specific_fields["thinking_blocks"] = thinking_blocks + elif "content" in content_block["delta"] and content_block["delta"].get("type") == "compaction_delta": + # Handle compaction delta + provider_specific_fields["compaction_delta"] = { + "type": "compaction_delta", + "content": content_block["delta"]["content"] + } return text, tool_use, thinking_blocks, provider_specific_fields @@ -721,6 +730,20 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: # noqa: PLR0915 provider_specific_fields=provider_specific_fields, ) + elif content_block_start["content_block"]["type"] == "compaction": + # Handle compaction blocks + # The full content comes in content_block_start + self.compaction_blocks.append( + content_block_start["content_block"] + ) + provider_specific_fields["compaction_blocks"] = ( + self.compaction_blocks + ) + provider_specific_fields["compaction_start"] = { + "type": "compaction", + "content": content_block_start["content_block"].get("content", "") + } + elif content_block_start["content_block"]["type"].endswith("_tool_result"): # Handle all tool result types (web_search, bash_code_execution, text_editor, etc.) content_type = content_block_start["content_block"]["type"] diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py index 1b61b533275..02b8d952445 100644 --- a/litellm/llms/anthropic/chat/transformation.py +++ b/litellm/llms/anthropic/chat/transformation.py @@ -170,9 +170,10 @@ def convert_tool_use_to_openai_format( tool_call["caller"] = cast(Dict[str, Any], anthropic_tool_content["caller"]) # type: ignore[typeddict-item] return tool_call - def _is_claude_opus_4_5(self, model: str) -> bool: + @staticmethod + def _is_claude_opus_4_6(model: str) -> bool: """Check if the model is Claude Opus 4.5.""" - return "opus-4-5" in model.lower() or "opus_4_5" in model.lower() + return "opus-4-6" in model.lower() or "opus_4_6" in model.lower() def get_supported_openai_params(self, model: str): params = [ @@ -659,32 +660,38 @@ def _map_stop_sequences( @staticmethod def _map_reasoning_effort( - reasoning_effort: Optional[Union[REASONING_EFFORT, str]], + reasoning_effort: Optional[Union[REASONING_EFFORT, str]], + model: str, ) -> Optional[AnthropicThinkingParam]: - if reasoning_effort is None: - return None - elif reasoning_effort == "low": - return AnthropicThinkingParam( - type="enabled", - budget_tokens=DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET, - ) - elif reasoning_effort == "medium": - return AnthropicThinkingParam( - type="enabled", - budget_tokens=DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET, - ) - elif reasoning_effort == "high": - return AnthropicThinkingParam( - type="enabled", - budget_tokens=DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET, - ) - elif reasoning_effort == "minimal": + if AnthropicConfig._is_claude_opus_4_6(model): return AnthropicThinkingParam( - type="enabled", - budget_tokens=DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET, + type="adaptive", ) else: - raise ValueError(f"Unmapped reasoning effort: {reasoning_effort}") + if reasoning_effort is None: + return None + elif reasoning_effort == "low": + return AnthropicThinkingParam( + type="enabled", + budget_tokens=DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET, + ) + elif reasoning_effort == "medium": + return AnthropicThinkingParam( + type="enabled", + budget_tokens=DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET, + ) + elif reasoning_effort == "high": + return AnthropicThinkingParam( + type="enabled", + budget_tokens=DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET, + ) + elif reasoning_effort == "minimal": + return AnthropicThinkingParam( + type="enabled", + budget_tokens=DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET, + ) + else: + raise ValueError(f"Unmapped reasoning effort: {reasoning_effort}") def _extract_json_schema_from_response_format( self, value: Optional[dict] @@ -860,13 +867,8 @@ def map_openai_params( # noqa: PLR0915 if param == "thinking": optional_params["thinking"] = value elif param == "reasoning_effort" and isinstance(value, str): - # For Claude Opus 4.5, map reasoning_effort to output_config - if self._is_claude_opus_4_5(model): - optional_params["output_config"] = {"effort": value} - - # For other models, map to thinking parameter optional_params["thinking"] = AnthropicConfig._map_reasoning_effort( - value + reasoning_effort=value, model=model ) elif param == "web_search_options" and isinstance(value, dict): hosted_web_search_tool = self.map_web_search_tool( @@ -877,6 +879,9 @@ def map_openai_params( # noqa: PLR0915 ) elif param == "extra_headers": optional_params["extra_headers"] = value + elif param == "context_management" and isinstance(value, dict): + # Pass through Anthropic-specific context_management parameter + optional_params["context_management"] = value ## handle thinking tokens self.update_optional_params_with_thinking_tokens( @@ -1026,9 +1031,37 @@ def _ensure_beta_header(self, headers: dict, beta_value: str) -> None: if beta_value not in existing_values: headers["anthropic-beta"] = f"{existing_beta}, {beta_value}" - def _ensure_context_management_beta_header(self, headers: dict) -> None: - beta_value = ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value - self._ensure_beta_header(headers, beta_value) + def _ensure_context_management_beta_header( + self, headers: dict, context_management: dict + ) -> None: + """ + Add appropriate beta headers based on context_management edits. + - If any edit has type "compact_20260112", add compact-2026-01-12 header + - For all other edits, add context-management-2025-06-27 header + """ + edits = context_management.get("edits", []) + + has_compact = False + has_other = False + + for edit in edits: + edit_type = edit.get("type", "") + if edit_type == "compact_20260112": + has_compact = True + else: + has_other = True + + # Add compact header if any compact edits exist + if has_compact: + self._ensure_beta_header( + headers, ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value + ) + + # Add context management header if any other edits exist + if has_other: + self._ensure_beta_header( + headers, ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value + ) def update_headers_with_optional_anthropic_beta( self, headers: dict, optional_params: dict @@ -1056,7 +1089,9 @@ def update_headers_with_optional_anthropic_beta( headers, ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value ) if optional_params.get("context_management") is not None: - self._ensure_context_management_beta_header(headers) + self._ensure_context_management_beta_header( + headers, optional_params["context_management"] + ) if optional_params.get("output_format") is not None: self._ensure_beta_header( headers, ANTHROPIC_BETA_HEADER_VALUES.STRUCTURED_OUTPUT_2025_09_25.value @@ -1225,6 +1260,7 @@ def extract_response_content(self, completion_response: dict) -> Tuple[ List[ChatCompletionToolCallChunk], Optional[List[Any]], Optional[List[Any]], + Optional[List[Any]], ]: text_content = "" citations: Optional[List[Any]] = None @@ -1237,6 +1273,7 @@ def extract_response_content(self, completion_response: dict) -> Tuple[ tool_calls: List[ChatCompletionToolCallChunk] = [] web_search_results: Optional[List[Any]] = None tool_results: Optional[List[Any]] = None + compaction_blocks: Optional[List[Any]] = None for idx, content in enumerate(completion_response["content"]): if content["type"] == "text": text_content += content["text"] @@ -1278,6 +1315,12 @@ def extract_response_content(self, completion_response: dict) -> Tuple[ thinking_blocks.append( cast(ChatCompletionRedactedThinkingBlock, content) ) + + ## COMPACTION + elif content["type"] == "compaction": + if compaction_blocks is None: + compaction_blocks = [] + compaction_blocks.append(content) ## CITATIONS if content.get("citations") is not None: @@ -1299,7 +1342,7 @@ def extract_response_content(self, completion_response: dict) -> Tuple[ if thinking_content is not None: reasoning_content += thinking_content - return text_content, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results + return text_content, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks def calculate_usage( self, @@ -1316,6 +1359,10 @@ def calculate_usage( cache_creation_token_details: Optional[CacheCreationTokenDetails] = None web_search_requests: Optional[int] = None tool_search_requests: Optional[int] = None + inference_geo: Optional[str] = None + if "inference_geo" in _usage and _usage["inference_geo"] is not None: + inference_geo = _usage["inference_geo"] + if ( "cache_creation_input_tokens" in _usage and _usage["cache_creation_input_tokens"] is not None @@ -1399,6 +1446,7 @@ def calculate_usage( if (web_search_requests is not None or tool_search_requests is not None) else None ), + inference_geo=inference_geo, ) return usage @@ -1442,6 +1490,7 @@ def transform_parsed_response( tool_calls, web_search_results, tool_results, + compaction_blocks, ) = self.extract_response_content(completion_response=completion_response) if ( @@ -1469,6 +1518,8 @@ def transform_parsed_response( provider_specific_fields["tool_results"] = tool_results if container is not None: provider_specific_fields["container"] = container + if compaction_blocks is not None: + provider_specific_fields["compaction_blocks"] = compaction_blocks _message = litellm.Message( tool_calls=tool_calls, @@ -1477,6 +1528,7 @@ def transform_parsed_response( thinking_blocks=thinking_blocks, reasoning_content=reasoning_content, ) + _message.provider_specific_fields = provider_specific_fields ## HANDLE JSON MODE - anthropic returns single function call json_mode_message = self._transform_response_for_json_mode( @@ -1507,18 +1559,7 @@ def transform_parsed_response( model_response.created = int(time.time()) model_response.model = completion_response["model"] - context_management_response = completion_response.get("context_management") - if context_management_response is not None: - _hidden_params["context_management"] = context_management_response - try: - model_response.__dict__["context_management"] = ( - context_management_response - ) - except Exception: - pass - model_response._hidden_params = _hidden_params - return model_response def get_prefix_prompt(self, messages: List[AllMessageValues]) -> Optional[str]: diff --git a/litellm/llms/anthropic/cost_calculation.py b/litellm/llms/anthropic/cost_calculation.py index 8f34eb00ce5..11b61cc92f0 100644 --- a/litellm/llms/anthropic/cost_calculation.py +++ b/litellm/llms/anthropic/cost_calculation.py @@ -22,10 +22,17 @@ def cost_per_token(model: str, usage: "Usage") -> Tuple[float, float]: Returns: Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd """ - return generic_cost_per_token( - model=model, usage=usage, custom_llm_provider="anthropic" + # If usage has inference_geo, prepend it as prefix to model name + if hasattr(usage, "inference_geo") and usage.inference_geo and usage.inference_geo.lower() not in ["global", "not_available"]: + model_with_geo_prefix = f"{usage.inference_geo}/{model}" + else: + model_with_geo_prefix = model + prompt_cost, completion_cost = generic_cost_per_token( + model=model_with_geo_prefix, usage=usage, custom_llm_provider="anthropic" ) + return prompt_cost, completion_cost + def get_cost_for_anthropic_web_search( model_info: Optional["ModelInfo"] = None, diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py index 8fa7bb7e65e..a17eba75b3b 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py @@ -6,6 +6,7 @@ Dict, List, Optional, + Tuple, Union, cast, ) @@ -47,8 +48,14 @@ def _prepare_completion_kwargs( top_p: Optional[float] = None, output_format: Optional[Dict] = None, extra_kwargs: Optional[Dict[str, Any]] = None, - ) -> Dict[str, Any]: - """Prepare kwargs for litellm.completion/acompletion""" + ) -> Tuple[Dict[str, Any], Dict[str, str]]: + """Prepare kwargs for litellm.completion/acompletion. + + Returns: + Tuple of (completion_kwargs, tool_name_mapping) + - tool_name_mapping maps truncated tool names back to original names + for tools that exceeded OpenAI's 64-char limit + """ from litellm.litellm_core_utils.litellm_logging import ( Logging as LiteLLMLoggingObject, ) @@ -80,7 +87,7 @@ def _prepare_completion_kwargs( if output_format: request_data["output_format"] = output_format - openai_request = ANTHROPIC_ADAPTER.translate_completion_input_params( + openai_request, tool_name_mapping = ANTHROPIC_ADAPTER.translate_completion_input_params_with_tool_mapping( request_data ) @@ -116,7 +123,7 @@ def _prepare_completion_kwargs( ): completion_kwargs[key] = value - return completion_kwargs + return completion_kwargs, tool_name_mapping @staticmethod async def async_anthropic_messages_handler( @@ -137,7 +144,7 @@ async def async_anthropic_messages_handler( **kwargs, ) -> Union[AnthropicMessagesResponse, AsyncIterator]: """Handle non-Anthropic models asynchronously using the adapter""" - completion_kwargs = ( + completion_kwargs, tool_name_mapping = ( LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs( max_tokens=max_tokens, messages=messages, @@ -164,6 +171,7 @@ async def async_anthropic_messages_handler( ANTHROPIC_ADAPTER.translate_completion_output_params_streaming( completion_response, model=model, + tool_name_mapping=tool_name_mapping, ) ) if transformed_stream is not None: @@ -172,7 +180,8 @@ async def async_anthropic_messages_handler( else: anthropic_response = ( ANTHROPIC_ADAPTER.translate_completion_output_params( - cast(ModelResponse, completion_response) + cast(ModelResponse, completion_response), + tool_name_mapping=tool_name_mapping, ) ) if anthropic_response is not None: @@ -222,7 +231,7 @@ def anthropic_messages_handler( **kwargs, ) - completion_kwargs = ( + completion_kwargs, tool_name_mapping = ( LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs( max_tokens=max_tokens, messages=messages, @@ -249,6 +258,7 @@ def anthropic_messages_handler( ANTHROPIC_ADAPTER.translate_completion_output_params_streaming( completion_response, model=model, + tool_name_mapping=tool_name_mapping, ) ) if transformed_stream is not None: @@ -257,7 +267,8 @@ def anthropic_messages_handler( else: anthropic_response = ( ANTHROPIC_ADAPTER.translate_completion_output_params( - cast(ModelResponse, completion_response) + cast(ModelResponse, completion_response), + tool_name_mapping=tool_name_mapping, ) ) if anthropic_response is not None: diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py index 24524233ddf..a86820f82e8 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py @@ -3,7 +3,7 @@ import json import traceback from collections import deque -from typing import TYPE_CHECKING, Any, AsyncIterator, Iterator, Literal, Optional +from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, Literal, Optional from litellm import verbose_logger from litellm._uuid import uuid @@ -44,9 +44,16 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): pending_new_content_block: bool = False chunk_queue: deque = deque() # Queue for buffering multiple chunks - def __init__(self, completion_stream: Any, model: str): + def __init__( + self, + completion_stream: Any, + model: str, + tool_name_mapping: Optional[Dict[str, str]] = None, + ): super().__init__(completion_stream) self.model = model + # Mapping of truncated tool names to original names (for OpenAI's 64-char limit) + self.tool_name_mapping = tool_name_mapping or {} def _create_initial_usage_delta(self) -> UsageDelta: """ @@ -401,6 +408,19 @@ def _should_start_new_content_block(self, chunk: "ModelResponseStream") -> bool: choices=chunk.choices # type: ignore ) + # Restore original tool name if it was truncated for OpenAI's 64-char limit + if block_type == "tool_use": + # Type narrowing: content_block_start is ToolUseBlock when block_type is "tool_use" + from typing import cast + from litellm.types.llms.anthropic import ToolUseBlock + + tool_block = cast(ToolUseBlock, content_block_start) + + if tool_block.get("name"): + truncated_name = tool_block["name"] + original_name = self.tool_name_mapping.get(truncated_name, truncated_name) + tool_block["name"] = original_name + if block_type != self.current_content_block_type: self.current_content_block_type = block_type self.current_content_block_start = content_block_start @@ -408,9 +428,14 @@ def _should_start_new_content_block(self, chunk: "ModelResponseStream") -> bool: # For parallel tool calls, we'll necessarily have a new content block # if we get a function name since it signals a new tool call - if block_type == "tool_use" and content_block_start.get("name"): - self.current_content_block_type = block_type - self.current_content_block_start = content_block_start - return True + if block_type == "tool_use": + from typing import cast + from litellm.types.llms.anthropic import ToolUseBlock + + tool_block = cast(ToolUseBlock, content_block_start) + if tool_block.get("name"): + self.current_content_block_type = block_type + self.current_content_block_start = content_block_start + return True return False diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py index 5ba0754b744..169b138a5f7 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py @@ -1,3 +1,4 @@ +import hashlib import json from typing import ( TYPE_CHECKING, @@ -12,6 +13,54 @@ cast, ) +# OpenAI has a 64-character limit for function/tool names +# Anthropic does not have this limit, so we need to truncate long names +OPENAI_MAX_TOOL_NAME_LENGTH = 64 +TOOL_NAME_HASH_LENGTH = 8 +TOOL_NAME_PREFIX_LENGTH = OPENAI_MAX_TOOL_NAME_LENGTH - TOOL_NAME_HASH_LENGTH - 1 # 55 + + +def truncate_tool_name(name: str) -> str: + """ + Truncate tool names that exceed OpenAI's 64-character limit. + + Uses format: {55-char-prefix}_{8-char-hash} to avoid collisions + when multiple tools have similar long names. + + Args: + name: The original tool name + + Returns: + The original name if <= 64 chars, otherwise truncated with hash + """ + if len(name) <= OPENAI_MAX_TOOL_NAME_LENGTH: + return name + + # Create deterministic hash from full name to avoid collisions + name_hash = hashlib.sha256(name.encode()).hexdigest()[:TOOL_NAME_HASH_LENGTH] + return f"{name[:TOOL_NAME_PREFIX_LENGTH]}_{name_hash}" + + +def create_tool_name_mapping( + tools: List[Dict[str, Any]], +) -> Dict[str, str]: + """ + Create a mapping of truncated tool names to original names. + + Args: + tools: List of tool definitions with 'name' field + + Returns: + Dict mapping truncated names to original names (only for truncated tools) + """ + mapping: Dict[str, str] = {} + for tool in tools: + original_name = tool.get("name", "") + truncated_name = truncate_tool_name(original_name) + if truncated_name != original_name: + mapping[truncated_name] = original_name + return mapping + from openai.types.chat.chat_completion_chunk import Choice as OpenAIStreamingChoice from litellm.litellm_core_utils.prompt_templates.common_utils import ( @@ -77,8 +126,29 @@ def translate_completion_input_params( self, kwargs ) -> Optional[ChatCompletionRequest]: """ + Translate Anthropic request params to OpenAI format. + - translate params, where needed - pass rest, as is + + Note: Use translate_completion_input_params_with_tool_mapping() if you need + the tool name mapping for restoring original names in responses. + """ + result, _ = self.translate_completion_input_params_with_tool_mapping(kwargs) + return result + + def translate_completion_input_params_with_tool_mapping( + self, kwargs + ) -> Tuple[Optional[ChatCompletionRequest], Dict[str, str]]: + """ + Translate Anthropic request params to OpenAI format, returning tool name mapping. + + This method handles truncation of tool names that exceed OpenAI's 64-character + limit. The mapping allows restoring original names when translating responses. + + Returns: + Tuple of (openai_request, tool_name_mapping) + - tool_name_mapping maps truncated tool names back to original names """ ######################################################### @@ -102,26 +172,51 @@ def translate_completion_input_params( model=model, messages=messages, **kwargs ) - translated_body = ( + translated_body, tool_name_mapping = ( LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( anthropic_message_request=request_body ) ) - return translated_body + return translated_body, tool_name_mapping def translate_completion_output_params( - self, response: ModelResponse + self, + response: ModelResponse, + tool_name_mapping: Optional[Dict[str, str]] = None, ) -> Optional[AnthropicMessagesResponse]: + """ + Translate OpenAI response to Anthropic format. + + Args: + response: The OpenAI ModelResponse + tool_name_mapping: Optional mapping of truncated tool names to original names. + Used to restore original names for tools that exceeded + OpenAI's 64-char limit. + """ return LiteLLMAnthropicMessagesAdapter().translate_openai_response_to_anthropic( - response=response + response=response, + tool_name_mapping=tool_name_mapping, ) def translate_completion_output_params_streaming( - self, completion_stream: Any, model: str + self, + completion_stream: Any, + model: str, + tool_name_mapping: Optional[Dict[str, str]] = None, ) -> Union[AsyncIterator[bytes], None]: + """ + Translate OpenAI streaming response to Anthropic format. + + Args: + completion_stream: The OpenAI streaming response + model: The model name + tool_name_mapping: Optional mapping of truncated tool names to original names. + """ anthropic_wrapper = AnthropicStreamWrapper( - completion_stream=completion_stream, model=model + completion_stream=completion_stream, + model=model, + tool_name_mapping=tool_name_mapping, ) # Return the SSE-wrapped version for proper event formatting return anthropic_wrapper.async_anthropic_sse_wrapper() @@ -417,8 +512,10 @@ def translate_anthropic_messages_to_openai( # noqa: PLR0915 has_cache_control_in_text = True assistant_content_list.append(text_block) elif content.get("type") == "tool_use": + # Truncate tool name for OpenAI's 64-char limit + tool_name = truncate_tool_name(content.get("name", "")) function_chunk: ChatCompletionToolCallFunctionChunk = { - "name": content.get("name", ""), + "name": tool_name, "arguments": json.dumps(content.get("input", {})), } signature = ( @@ -587,8 +684,11 @@ def translate_anthropic_tool_choice_to_openai( elif tool_choice["type"] == "auto": return "auto" elif tool_choice["type"] == "tool": + # Truncate tool name if it exceeds OpenAI's 64-char limit + original_name = tool_choice.get("name", "") + truncated_name = truncate_tool_name(original_name) tc_function_param = ChatCompletionToolChoiceFunctionParam( - name=tool_choice.get("name", "") + name=truncated_name ) return ChatCompletionToolChoiceObjectParam( type="function", function=tc_function_param @@ -600,12 +700,28 @@ def translate_anthropic_tool_choice_to_openai( def translate_anthropic_tools_to_openai( self, tools: List[AllAnthropicToolsValues], model: Optional[str] = None - ) -> List[ChatCompletionToolParam]: + ) -> Tuple[List[ChatCompletionToolParam], Dict[str, str]]: + """ + Translate Anthropic tools to OpenAI format. + + Returns: + Tuple of (translated_tools, tool_name_mapping) + - tool_name_mapping maps truncated names back to original names + for tools that exceeded OpenAI's 64-char limit + """ new_tools: List[ChatCompletionToolParam] = [] + tool_name_mapping: Dict[str, str] = {} mapped_tool_params = ["name", "input_schema", "description", "cache_control"] for tool in tools: + original_name = tool["name"] + truncated_name = truncate_tool_name(original_name) + + # Store mapping if name was truncated + if truncated_name != original_name: + tool_name_mapping[truncated_name] = original_name + function_chunk = ChatCompletionToolParamFunctionChunk( - name=tool["name"], + name=truncated_name, ) if "input_schema" in tool: function_chunk["parameters"] = tool["input_schema"] # type: ignore @@ -619,7 +735,7 @@ def translate_anthropic_tools_to_openai( self._add_cache_control_if_applicable(tool, tool_param, model) new_tools.append(tool_param) # type: ignore[arg-type] - return new_tools # type: ignore[return-value] + return new_tools, tool_name_mapping # type: ignore[return-value] def translate_anthropic_output_format_to_openai( self, output_format: Any @@ -694,12 +810,18 @@ def _add_system_message_to_messages( def translate_anthropic_to_openai( self, anthropic_message_request: AnthropicMessagesRequest - ) -> ChatCompletionRequest: + ) -> Tuple[ChatCompletionRequest, Dict[str, str]]: """ This is used by the beta Anthropic Adapter, for translating anthropic `/v1/messages` requests to the openai format. + + Returns: + Tuple of (openai_request, tool_name_mapping) + - tool_name_mapping maps truncated tool names back to original names + for tools that exceeded OpenAI's 64-char limit """ # Debug: Processing Anthropic message request new_messages: List[AllMessageValues] = [] + tool_name_mapping: Dict[str, str] = {} ## CONVERT ANTHROPIC MESSAGES TO OPENAI messages_list: List[ @@ -750,7 +872,7 @@ def translate_anthropic_to_openai( if "tools" in anthropic_message_request: tools = anthropic_message_request["tools"] if tools: - new_kwargs["tools"] = self.translate_anthropic_tools_to_openai( + new_kwargs["tools"], tool_name_mapping = self.translate_anthropic_tools_to_openai( tools=cast(List[AllAnthropicToolsValues], tools), model=new_kwargs.get("model"), ) @@ -784,7 +906,7 @@ def translate_anthropic_to_openai( if k not in translatable_params: # pass remaining params as is new_kwargs[k] = v # type: ignore - return new_kwargs + return new_kwargs, tool_name_mapping def _translate_anthropic_image_to_openai(self, image_source: dict) -> Optional[str]: """ @@ -813,22 +935,12 @@ def _translate_anthropic_image_to_openai(self, image_source: dict) -> Optional[s return None - def _translate_openai_content_to_anthropic(self, choices: List[Choices]) -> List[ - Union[ - AnthropicResponseContentBlockText, - AnthropicResponseContentBlockToolUse, - AnthropicResponseContentBlockThinking, - AnthropicResponseContentBlockRedactedThinking, - ] - ]: - new_content: List[ - Union[ - AnthropicResponseContentBlockText, - AnthropicResponseContentBlockToolUse, - AnthropicResponseContentBlockThinking, - AnthropicResponseContentBlockRedactedThinking, - ] - ] = [] + def _translate_openai_content_to_anthropic( + self, + choices: List[Choices], + tool_name_mapping: Optional[Dict[str, str]] = None, + ) -> List[Dict[str, Any]]: + new_content: List[Dict[str, Any]] = [] for choice in choices: # Handle thinking blocks first if ( @@ -852,7 +964,7 @@ def _translate_openai_content_to_anthropic(self, choices: List[Choices]) -> List if signature_value is not None else None ), - ) + ).model_dump() ) elif thinking_block.get("type") == "redacted_thinking": data_value = thinking_block.get("data", "") @@ -860,15 +972,27 @@ def _translate_openai_content_to_anthropic(self, choices: List[Choices]) -> List AnthropicResponseContentBlockRedactedThinking( type="redacted_thinking", data=str(data_value) if data_value is not None else "", - ) + ).model_dump() ) + # Handle reasoning_content when thinking_blocks is not present + elif ( + hasattr(choice.message, "reasoning_content") + and choice.message.reasoning_content + ): + new_content.append( + AnthropicResponseContentBlockThinking( + type="thinking", + thinking=str(choice.message.reasoning_content), + signature=None, + ).model_dump() + ) # Handle text content if choice.message.content is not None: new_content.append( AnthropicResponseContentBlockText( type="text", text=choice.message.content - ) + ).model_dump() ) # Handle tool calls (in parallel to text content) if ( @@ -883,13 +1007,21 @@ def _translate_openai_content_to_anthropic(self, choices: List[Choices]) -> List if signature: provider_specific_fields["signature"] = signature + # Restore original tool name if it was truncated + truncated_name = tool_call.function.name or "" + original_name = ( + tool_name_mapping.get(truncated_name, truncated_name) + if tool_name_mapping + else truncated_name + ) + tool_use_block = AnthropicResponseContentBlockToolUse( type="tool_use", id=tool_call.id, - name=tool_call.function.name or "", + name=original_name, input=parse_tool_call_arguments( tool_call.function.arguments, - tool_name=tool_call.function.name, + tool_name=original_name, context="Anthropic pass-through adapter", ), ) @@ -898,7 +1030,7 @@ def _translate_openai_content_to_anthropic(self, choices: List[Choices]) -> List tool_use_block.provider_specific_fields = ( provider_specific_fields ) - new_content.append(tool_use_block) + new_content.append(tool_use_block.model_dump()) return new_content @@ -914,10 +1046,24 @@ def _translate_openai_finish_reason_to_anthropic( return "end_turn" def translate_openai_response_to_anthropic( - self, response: ModelResponse + self, + response: ModelResponse, + tool_name_mapping: Optional[Dict[str, str]] = None, ) -> AnthropicMessagesResponse: + """ + Translate OpenAI response to Anthropic format. + + Args: + response: The OpenAI ModelResponse + tool_name_mapping: Optional mapping of truncated tool names to original names. + Used to restore original names for tools that exceeded + OpenAI's 64-char limit. + """ ## translate content block - anthropic_content = self._translate_openai_content_to_anthropic(choices=response.choices) # type: ignore + anthropic_content = self._translate_openai_content_to_anthropic( + choices=response.choices, # type: ignore + tool_name_mapping=tool_name_mapping, + ) ## extract finish reason anthropic_finish_reason = self._translate_openai_finish_reason_to_anthropic( openai_finish_reason=response.choices[0].finish_reason # type: ignore @@ -1036,6 +1182,13 @@ def _translate_streaming_openai_chunk_to_anthropic( reasoning_content += thinking reasoning_signature += signature + # Handle reasoning_content when thinking_blocks is not present + # This handles providers like OpenRouter that return reasoning_content + elif isinstance(choice, StreamingChoices) and hasattr( + choice.delta, "reasoning_content" + ): + if choice.delta.reasoning_content is not None: + reasoning_content += choice.delta.reasoning_content if reasoning_content and reasoning_signature: raise ValueError( diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py index 308bf367d06..bb40f9df266 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py @@ -2,6 +2,9 @@ import httpx +from litellm.anthropic_beta_headers_manager import ( + update_headers_with_filtered_beta, +) from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj from litellm.litellm_core_utils.litellm_logging import verbose_logger from litellm.llms.base_llm.anthropic_messages.transformation import ( @@ -90,6 +93,11 @@ def validate_anthropic_messages_environment( optional_params=optional_params, ) + headers = update_headers_with_filtered_beta( + headers=headers, + provider="anthropic", + ) + return headers, api_base def transform_anthropic_messages_request( @@ -189,8 +197,27 @@ def _update_headers_with_anthropic_beta( beta_values.update(b.strip() for b in existing_beta.split(",")) # Check for context management - if optional_params.get("context_management") is not None: - beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value) + context_management_param = optional_params.get("context_management") + if context_management_param is not None: + # Check edits array for compact_20260112 type + edits = context_management_param.get("edits", []) + has_compact = False + has_other = False + + for edit in edits: + edit_type = edit.get("type", "") + if edit_type == "compact_20260112": + has_compact = True + else: + has_other = True + + # Add compact header if any compact edits exist + if has_compact: + beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value) + + # Add context management header if any other edits exist + if has_other: + beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value) # Check for structured outputs if optional_params.get("output_format") is not None: diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py b/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py index e284595cc8a..09b83b7c971 100644 --- a/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py +++ b/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py @@ -30,30 +30,32 @@ def get_required_headers( """ Get the required headers for the Azure AI Anthropic CountTokens API. - Uses Azure authentication (api-key header) instead of Anthropic's x-api-key. + Azure AI Anthropic uses Anthropic's native API format, which requires the + x-api-key header for authentication (in addition to Azure's api-key header). Args: api_key: The Azure AI API key litellm_params: Optional LiteLLM parameters for additional auth config Returns: - Dictionary of required headers with Azure authentication + Dictionary of required headers with both x-api-key and Azure authentication """ - # Start with base headers + # Start with base headers including x-api-key for Anthropic API compatibility headers = { "Content-Type": "application/json", "anthropic-version": "2023-06-01", "anthropic-beta": ANTHROPIC_TOKEN_COUNTING_BETA_VERSION, + "x-api-key": api_key, # Azure AI Anthropic requires this header } - # Use Azure authentication + # Also set up Azure auth headers for flexibility litellm_params = litellm_params or {} if "api_key" not in litellm_params: litellm_params["api_key"] = api_key litellm_params_obj = GenericLiteLLMParams(**litellm_params) - # Get Azure auth headers + # Get Azure auth headers (api-key or Authorization) azure_headers = BaseAzureLLM._base_validate_azure_environment( headers={}, litellm_params=litellm_params_obj ) @@ -68,7 +70,7 @@ def get_count_tokens_endpoint(self, api_base: str) -> str: Get the Azure AI Anthropic CountTokens API endpoint. Args: - api_base: The Azure AI API base URL + api_base: The Azure AI API base URL (e.g., https://my-resource.services.ai.azure.com or https://my-resource.services.ai.azure.com/anthropic) diff --git a/litellm/llms/azure_ai/anthropic/transformation.py b/litellm/llms/azure_ai/anthropic/transformation.py index 2d8d3b987c7..753bc9c08eb 100644 --- a/litellm/llms/azure_ai/anthropic/transformation.py +++ b/litellm/llms/azure_ai/anthropic/transformation.py @@ -3,6 +3,9 @@ """ from typing import TYPE_CHECKING, Dict, List, Optional, Union +from litellm.anthropic_beta_headers_manager import ( + update_headers_with_filtered_beta, +) from litellm.llms.anthropic.chat.transformation import AnthropicConfig from litellm.llms.azure.common_utils import BaseAzureLLM from litellm.types.llms.openai import AllMessageValues @@ -87,6 +90,12 @@ def validate_environment( if "anthropic-version" not in headers: headers["anthropic-version"] = "2023-06-01" + # Filter out unsupported beta headers for Azure AI + headers = update_headers_with_filtered_beta( + headers=headers, + provider="azure_ai", + ) + return headers def transform_request( diff --git a/litellm/llms/azure_ai/rerank/transformation.py b/litellm/llms/azure_ai/rerank/transformation.py index a47b6082c37..f577a42ed58 100644 --- a/litellm/llms/azure_ai/rerank/transformation.py +++ b/litellm/llms/azure_ai/rerank/transformation.py @@ -11,6 +11,7 @@ from litellm.llms.cohere.rerank.transformation import CohereRerankConfig from litellm.secret_managers.main import get_secret_str from litellm.types.utils import RerankResponse +from litellm.utils import _add_path_to_api_base class AzureAIRerankConfig(CohereRerankConfig): @@ -28,9 +29,34 @@ def get_complete_url( raise ValueError( "Azure AI API Base is required. api_base=None. Set in call or via `AZURE_AI_API_BASE` env var." ) - if not api_base.endswith("/v1/rerank"): - api_base = f"{api_base}/v1/rerank" - return api_base + original_url = httpx.URL(api_base) + if not original_url.is_absolute_url: + raise ValueError( + "Azure AI API Base must be an absolute URL including scheme (e.g. " + "'https://.services.ai.azure.com'). " + f"Got api_base={api_base!r}." + ) + normalized_path = original_url.path.rstrip("/") + + # Allow callers to pass either full v1/v2 rerank endpoints: + # - https://.services.ai.azure.com/v1/rerank + # - https://.services.ai.azure.com/providers/cohere/v2/rerank + if normalized_path.endswith("/v1/rerank") or normalized_path.endswith("/v2/rerank"): + return str(original_url.copy_with(path=normalized_path or "/")) + + # If callers pass just the version path (e.g. ".../v2" or ".../providers/cohere/v2"), append "/rerank" + if ( + normalized_path.endswith("/v1") + or normalized_path.endswith("/v2") + or normalized_path.endswith("/providers/cohere/v2") + ): + return _add_path_to_api_base( + api_base=str(original_url.copy_with(path=normalized_path or "/")), + ending_path="/rerank", + ) + + # Backwards compatible default: Azure AI rerank was originally exposed under /v1/rerank + return _add_path_to_api_base(api_base=api_base, ending_path="/v1/rerank") def validate_environment( self, diff --git a/litellm/llms/bedrock/chat/converse_handler.py b/litellm/llms/bedrock/chat/converse_handler.py index d5bd054118d..0a56ea63d36 100644 --- a/litellm/llms/bedrock/chat/converse_handler.py +++ b/litellm/llms/bedrock/chat/converse_handler.py @@ -66,7 +66,7 @@ def make_sync_call( model_response=model_response, json_mode=json_mode ) else: - decoder = AWSEventStreamDecoder(model=model) + decoder = AWSEventStreamDecoder(model=model, json_mode=json_mode) completion_stream = decoder.iter_bytes(response.iter_bytes(chunk_size=stream_chunk_size)) # LOGGING diff --git a/litellm/llms/bedrock/chat/converse_transformation.py b/litellm/llms/bedrock/chat/converse_transformation.py index d4e4d3591ba..3d63a701901 100644 --- a/litellm/llms/bedrock/chat/converse_transformation.py +++ b/litellm/llms/bedrock/chat/converse_transformation.py @@ -3,6 +3,7 @@ """ import copy +import json import time import types from typing import List, Literal, Optional, Tuple, Union, cast, overload @@ -11,6 +12,9 @@ import litellm from litellm._logging import verbose_logger +from litellm.anthropic_beta_headers_manager import ( + filter_and_transform_beta_headers, +) from litellm.constants import RESPONSE_FORMAT_TOOL_NAME from litellm.litellm_core_utils.core_helpers import ( filter_exceptions_from_params, @@ -66,6 +70,7 @@ BedrockModelInfo, get_anthropic_beta_from_headers, get_bedrock_tool_name, + is_claude_4_5_on_bedrock, ) # Computer use tool prefixes supported by Bedrock @@ -81,6 +86,7 @@ UNSUPPORTED_BEDROCK_CONVERSE_BETA_PATTERNS = [ "advanced-tool-use", # Bedrock Converse doesn't support advanced-tool-use beta headers "prompt-caching", # Prompt caching not supported in Converse API + "compact-2026-01-12", # The compact beta feature is not currently supported on the Converse and ConverseStream APIs ] @@ -306,9 +312,7 @@ def _is_nova_lite_2_model(self, model: str) -> bool: return "nova-2-lite" in model_without_region def _map_web_search_options( - self, - web_search_options: dict, - model: str + self, web_search_options: dict, model: str ) -> Optional[BedrockToolBlock]: """ Map web_search_options to Nova grounding systemTool. @@ -431,7 +435,7 @@ def _handle_reasoning_effort_parameter( else: # Anthropic and other models: convert to thinking parameter optional_params["thinking"] = AnthropicConfig._map_reasoning_effort( - reasoning_effort + reasoning_effort=reasoning_effort, model=model ) def get_supported_openai_params(self, model: str) -> List[str]: @@ -617,37 +621,6 @@ def _transform_computer_use_tools( return transformed_tools - def _filter_unsupported_beta_headers_for_bedrock( - self, model: str, beta_list: list - ) -> list: - """ - Remove beta headers that are not supported on Bedrock Converse API for the given model. - - Extended thinking beta headers are only supported on specific Claude 4+ models. - Some beta headers are universally unsupported on Bedrock Converse API. - - Args: - model: The model name - beta_list: The list of beta headers to filter - - Returns: - Filtered list of beta headers - """ - filtered_betas = [] - - # 1. Filter out beta headers that are universally unsupported on Bedrock Converse - for beta in beta_list: - should_keep = True - for unsupported_pattern in UNSUPPORTED_BEDROCK_CONVERSE_BETA_PATTERNS: - if unsupported_pattern in beta.lower(): - should_keep = False - break - - if should_keep: - filtered_betas.append(beta) - - return filtered_betas - def _separate_computer_use_tools( self, tools: List[OpenAIChatCompletionToolParam], model: str ) -> Tuple[ @@ -808,11 +781,11 @@ def map_openai_params( if param == "web_search_options" and isinstance(value, dict): # Note: we use `isinstance(value, dict)` instead of `value and isinstance(value, dict)` # because empty dict {} is falsy but is a valid way to enable Nova grounding - grounding_tool = self._map_web_search_options(value, model) - if grounding_tool is not None: - optional_params = self._add_tools_to_optional_params( - optional_params=optional_params, tools=[grounding_tool] - ) + grounding_tool = self._map_web_search_options(value, model) + if grounding_tool is not None: + optional_params = self._add_tools_to_optional_params( + optional_params=optional_params, tools=[grounding_tool] + ) # Only update thinking tokens for non-GPT-OSS models and non-Nova-Lite-2 models # Nova Lite 2 handles token budgeting differently through reasoningConfig @@ -926,6 +899,7 @@ def _get_cache_point_block( ChatCompletionAssistantMessage, ], block_type: Literal["system"], + model: Optional[str] = None, ) -> Optional[SystemContentBlock]: pass @@ -939,6 +913,7 @@ def _get_cache_point_block( ChatCompletionAssistantMessage, ], block_type: Literal["content_block"], + model: Optional[str] = None, ) -> Optional[ContentBlock]: pass @@ -951,16 +926,26 @@ def _get_cache_point_block( ChatCompletionAssistantMessage, ], block_type: Literal["system", "content_block"], + model: Optional[str] = None, ) -> Optional[Union[SystemContentBlock, ContentBlock]]: - if message_block.get("cache_control", None) is None: + cache_control = message_block.get("cache_control", None) + if cache_control is None: return None + + cache_point = CachePointBlock(type="default") + if isinstance(cache_control, dict) and "ttl" in cache_control: + ttl = cache_control["ttl"] + if ttl in ["5m", "1h"] and model is not None: + if is_claude_4_5_on_bedrock(model): + cache_point["ttl"] = ttl + if block_type == "system": - return SystemContentBlock(cachePoint=CachePointBlock(type="default")) + return SystemContentBlock(cachePoint=cache_point) else: - return ContentBlock(cachePoint=CachePointBlock(type="default")) + return ContentBlock(cachePoint=cache_point) def _transform_system_message( - self, messages: List[AllMessageValues] + self, messages: List[AllMessageValues], model: Optional[str] = None ) -> Tuple[List[AllMessageValues], List[SystemContentBlock]]: system_prompt_indices = [] system_content_blocks: List[SystemContentBlock] = [] @@ -972,7 +957,7 @@ def _transform_system_message( SystemContentBlock(text=message["content"]) ) cache_block = self._get_cache_point_block( - message, block_type="system" + message, block_type="system", model=model ) if cache_block: system_content_blocks.append(cache_block) @@ -983,7 +968,7 @@ def _transform_system_message( SystemContentBlock(text=m["text"]) ) cache_block = self._get_cache_point_block( - m, block_type="system" + m, block_type="system", model=model ) if cache_block: system_content_blocks.append(cache_block) @@ -1081,10 +1066,16 @@ def _process_tools_and_beta( user_betas = get_anthropic_beta_from_headers(headers) anthropic_beta_list.extend(user_betas) - # Filter out tool search tools - Bedrock Converse API doesn't support them + # Separate pre-formatted Bedrock tools (e.g. systemTool from web_search_options) + # from OpenAI-format tools that need transformation via _bedrock_tools_pt filtered_tools = [] + pre_formatted_tools: List[ToolBlock] = [] if original_tools: for tool in original_tools: + # Already-formatted Bedrock tools (e.g. systemTool for Nova grounding) + if "systemTool" in tool: + pre_formatted_tools.append(tool) + continue tool_type = tool.get("type", "") if tool_type in ( "tool_search_tool_regex_20251119", @@ -1106,7 +1097,28 @@ def _process_tools_and_beta( # Add computer use tools and anthropic_beta if needed (only when computer use tools are present) if computer_use_tools: - anthropic_beta_list.append("computer-use-2024-10-22") + # Determine the correct computer-use beta header based on model + # "computer-use-2025-11-24" for Claude Opus 4.6, Claude Opus 4.5 + # "computer-use-2025-01-24" for Claude Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4, and Sonnet 3.7 + # "computer-use-2024-10-22" for older models + model_lower = model.lower() + if "opus-4.6" in model_lower or "opus_4.6" in model_lower or "opus-4-6" in model_lower or "opus_4_6" in model_lower: + computer_use_header = "computer-use-2025-11-24" + elif "opus-4.5" in model_lower or "opus_4.5" in model_lower or "opus-4-5" in model_lower or "opus_4_5" in model_lower: + computer_use_header = "computer-use-2025-11-24" + elif any(pattern in model_lower for pattern in [ + "sonnet-4.5", "sonnet_4.5", "sonnet-4-5", "sonnet_4_5", + "haiku-4.5", "haiku_4.5", "haiku-4-5", "haiku_4_5", + "opus-4.1", "opus_4.1", "opus-4-1", "opus_4_1", + "sonnet-4", "sonnet_4", + "opus-4", "opus_4", + "sonnet-3.7", "sonnet_3.7", "sonnet-3-7", "sonnet_3_7" + ]): + computer_use_header = "computer-use-2025-01-24" + else: + computer_use_header = "computer-use-2024-10-22" + + anthropic_beta_list.append(computer_use_header) # Transform computer use tools to proper Bedrock format transformed_computer_tools = self._transform_computer_use_tools( computer_use_tools @@ -1116,6 +1128,9 @@ def _process_tools_and_beta( # No computer use tools, process all tools as regular tools bedrock_tools = _bedrock_tools_pt(filtered_tools) + # Append pre-formatted tools (systemTool etc.) after transformation + bedrock_tools.extend(pre_formatted_tools) + # Set anthropic_beta in additional_request_params if we have any beta features # ONLY apply to Anthropic/Claude models - other models (e.g., Qwen, Llama) don't support this field # and will error with "unknown variant anthropic_beta" if included @@ -1128,14 +1143,14 @@ def _process_tools_and_beta( if beta not in seen: unique_betas.append(beta) seen.add(beta) - - # Filter out unsupported beta headers for Bedrock Converse API - filtered_betas = self._filter_unsupported_beta_headers_for_bedrock( - model=model, - beta_list=unique_betas, + + filtered_betas = filter_and_transform_beta_headers( + beta_headers=unique_betas, + provider="bedrock_converse", ) - additional_request_params["anthropic_beta"] = filtered_betas + if filtered_betas: + additional_request_params["anthropic_beta"] = filtered_betas return bedrock_tools, anthropic_beta_list @@ -1187,9 +1202,11 @@ def _transform_request_helper( ) # Prepare and separate parameters - inference_params, additional_request_params, request_metadata = self._prepare_request_params( - optional_params, model - ) + ( + inference_params, + additional_request_params, + request_metadata, + ) = self._prepare_request_params(optional_params, model) original_tools = inference_params.pop("tools", []) @@ -1241,7 +1258,9 @@ async def _async_transform_request( litellm_params: dict, headers: Optional[dict] = None, ) -> RequestObject: - messages, system_content_blocks = self._transform_system_message(messages) + messages, system_content_blocks = self._transform_system_message( + messages, model=model + ) # Convert last user message to guarded_text if guardrailConfig is present messages = self._convert_consecutive_user_messages_to_guarded_text( @@ -1297,7 +1316,9 @@ def _transform_request( litellm_params: dict, headers: Optional[dict] = None, ) -> RequestObject: - messages, system_content_blocks = self._transform_system_message(messages) + messages, system_content_blocks = self._transform_system_message( + messages, model=model + ) # Convert last user message to guarded_text if guardrailConfig is present messages = self._convert_consecutive_user_messages_to_guarded_text( @@ -1475,7 +1496,9 @@ def apply_tool_call_transformation_if_needed( return message, returned_finish_reason - def _translate_message_content(self, content_blocks: List[ContentBlock]) -> Tuple[ + def _translate_message_content( + self, content_blocks: List[ContentBlock] + ) -> Tuple[ str, List[ChatCompletionToolCallChunk], Optional[List[BedrockConverseReasoningContentBlock]], @@ -1492,9 +1515,9 @@ def _translate_message_content(self, content_blocks: List[ContentBlock]) -> Tupl """ content_str = "" tools: List[ChatCompletionToolCallChunk] = [] - reasoningContentBlocks: Optional[List[BedrockConverseReasoningContentBlock]] = ( - None - ) + reasoningContentBlocks: Optional[ + List[BedrockConverseReasoningContentBlock] + ] = None citationsContentBlocks: Optional[List[CitationsContentBlock]] = None for idx, content in enumerate(content_blocks): """ @@ -1548,7 +1571,71 @@ def _translate_message_content(self, content_blocks: List[ContentBlock]) -> Tupl return content_str, tools, reasoningContentBlocks, citationsContentBlocks - def _transform_response( # noqa: PLR0915 + def _filter_json_mode_tools( + self, + tools: List[ChatCompletionToolCallChunk], + json_mode: Optional[bool], + chat_completion_message: ChatCompletionResponseMessage, + ) -> Optional[List[ChatCompletionToolCallChunk]]: + """ + Filter out json_tool_call from tools if json_mode is enabled. + Handles the case where both real tools and response_format are used together. + + Returns None when json_tool_call was converted to content (caller should not set tool_calls). + Returns the (possibly filtered) list of tools otherwise. + """ + if not (json_mode is True and tools): + return tools # No filtering needed, return as-is (including empty list) + + # Check if json_tool_call is present + json_tool_call_index = None + for idx, tool in enumerate(tools): + if tool["function"].get("name") == RESPONSE_FORMAT_TOOL_NAME: + json_tool_call_index = idx + break + + if json_tool_call_index is None: + return tools # No json_tool_call found, return as-is + + # If json_tool_call is the ONLY tool, convert it to content (existing behavior) + if len(tools) == 1: + verbose_logger.debug( + "Processing JSON tool call response for response_format (single tool)" + ) + json_mode_content_str: Optional[str] = tools[0]["function"].get( + "arguments" + ) + if json_mode_content_str is not None: + # Bedrock returns the response wrapped in a "properties" object + # We need to extract the actual content from this wrapper + try: + response_data = json.loads(json_mode_content_str) + + # If Bedrock wrapped the response in "properties", extract the content + if ( + isinstance(response_data, dict) + and "properties" in response_data + and len(response_data) == 1 + ): + response_data = response_data["properties"] + json_mode_content_str = json.dumps(response_data) + except json.JSONDecodeError: + # If parsing fails, use the original response + pass + + chat_completion_message["content"] = json_mode_content_str + return None # Signal: don't set tool_calls + + # Multiple tools with json_tool_call present: filter it out + verbose_logger.debug( + "Filtering out %s from tool calls (multiple tools present)", + RESPONSE_FORMAT_TOOL_NAME, + ) + return [ + tool for idx, tool in enumerate(tools) if idx != json_tool_call_index + ] + + def _transform_response( # noqa: PLR0915 self, model: str, response: httpx.Response, @@ -1570,7 +1657,7 @@ def _transform_response( # noqa: PLR0915 additional_args={"complete_input_dict": data}, ) - json_mode: Optional[bool] = optional_params.pop("json_mode", None) + json_mode: Optional[bool] = optional_params.get("json_mode", None) ## RESPONSE OBJECT try: completion_response = ConverseResponseBlock(**response.json()) # type: ignore @@ -1621,9 +1708,9 @@ def _transform_response( # noqa: PLR0915 chat_completion_message: ChatCompletionResponseMessage = {"role": "assistant"} content_str = "" tools: List[ChatCompletionToolCallChunk] = [] - reasoningContentBlocks: Optional[List[BedrockConverseReasoningContentBlock]] = ( - None - ) + reasoningContentBlocks: Optional[ + List[BedrockConverseReasoningContentBlock] + ] = None citationsContentBlocks: Optional[List[CitationsContentBlock]] = None if message is not None: @@ -1642,49 +1729,30 @@ def _transform_response( # noqa: PLR0915 provider_specific_fields["citationsContent"] = citationsContentBlocks if provider_specific_fields: - chat_completion_message["provider_specific_fields"] = provider_specific_fields + chat_completion_message[ + "provider_specific_fields" + ] = provider_specific_fields if reasoningContentBlocks is not None: - chat_completion_message["reasoning_content"] = ( - self._transform_reasoning_content(reasoningContentBlocks) - ) - chat_completion_message["thinking_blocks"] = ( - self._transform_thinking_blocks(reasoningContentBlocks) - ) + chat_completion_message[ + "reasoning_content" + ] = self._transform_reasoning_content(reasoningContentBlocks) + chat_completion_message[ + "thinking_blocks" + ] = self._transform_thinking_blocks(reasoningContentBlocks) chat_completion_message["content"] = content_str - if ( - json_mode is True - and tools is not None - and len(tools) == 1 - and tools[0]["function"].get("name") == RESPONSE_FORMAT_TOOL_NAME - ): - verbose_logger.debug( - "Processing JSON tool call response for response_format" - ) - json_mode_content_str: Optional[str] = tools[0]["function"].get("arguments") - if json_mode_content_str is not None: - import json - # Bedrock returns the response wrapped in a "properties" object - # We need to extract the actual content from this wrapper - try: - response_data = json.loads(json_mode_content_str) - - # If Bedrock wrapped the response in "properties", extract the content - if ( - isinstance(response_data, dict) - and "properties" in response_data - and len(response_data) == 1 - ): - response_data = response_data["properties"] - json_mode_content_str = json.dumps(response_data) - except json.JSONDecodeError: - # If parsing fails, use the original response - pass + # Filter out json_tool_call from tools if json_mode is enabled + filtered_tools = self._filter_json_mode_tools( + tools=tools, + json_mode=json_mode, + chat_completion_message=chat_completion_message, + ) - chat_completion_message["content"] = json_mode_content_str - else: - chat_completion_message["tool_calls"] = tools + # None means json_tool_call was the only tool and was converted to content. + # Otherwise set tool_calls (including empty list, preserving original behavior). + if filtered_tools is not None: + chat_completion_message["tool_calls"] = filtered_tools ## CALCULATING USAGE - bedrock returns usage in the headers usage = self._transform_usage(completion_response["usage"]) diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.py index 1c58a11eebe..f3070d0a83d 100644 --- a/litellm/llms/bedrock/chat/invoke_handler.py +++ b/litellm/llms/bedrock/chat/invoke_handler.py @@ -72,6 +72,7 @@ bedrock_tool_name_mappings: InMemoryCache = InMemoryCache( max_size_in_memory=50, default_ttl=600 ) +from litellm.constants import RESPONSE_FORMAT_TOOL_NAME from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig from litellm.llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import ( AmazonBedrockOpenAIConfig, @@ -252,7 +253,7 @@ async def make_call( response.aiter_bytes(chunk_size=stream_chunk_size) ) else: - decoder = AWSEventStreamDecoder(model=model) + decoder = AWSEventStreamDecoder(model=model, json_mode=json_mode) completion_stream = decoder.aiter_bytes( response.aiter_bytes(chunk_size=stream_chunk_size) ) @@ -346,7 +347,7 @@ def make_sync_call( response.iter_bytes(chunk_size=stream_chunk_size) ) else: - decoder = AWSEventStreamDecoder(model=model) + decoder = AWSEventStreamDecoder(model=model, json_mode=json_mode) completion_stream = decoder.iter_bytes( response.iter_bytes(chunk_size=stream_chunk_size) ) @@ -1282,7 +1283,7 @@ def get_response_stream_shape(): class AWSEventStreamDecoder: - def __init__(self, model: str) -> None: + def __init__(self, model: str, json_mode: Optional[bool] = False) -> None: from botocore.parsers import EventStreamJSONParser self.model = model @@ -1290,6 +1291,8 @@ def __init__(self, model: str) -> None: self.content_blocks: List[ContentBlockDeltaEvent] = [] self.tool_calls_index: Optional[int] = None self.response_id: Optional[str] = None + self.json_mode = json_mode + self._current_block_is_json_tool_call = False def check_empty_tool_call_args(self) -> bool: """ @@ -1384,6 +1387,7 @@ def _handle_converse_start_event( ] = None self.content_blocks = [] # reset + self._current_block_is_json_tool_call = False if start_obj is not None: if "toolUse" in start_obj and start_obj["toolUse"] is not None: ## check tool name was formatted by litellm @@ -1391,18 +1395,33 @@ def _handle_converse_start_event( response_tool_name = get_bedrock_tool_name( response_tool_name=_response_tool_name ) - self.tool_calls_index = ( - 0 if self.tool_calls_index is None else self.tool_calls_index + 1 - ) - tool_use = { - "id": start_obj["toolUse"]["toolUseId"], - "type": "function", - "function": { - "name": response_tool_name, - "arguments": "", - }, - "index": self.tool_calls_index, - } + + # If json_mode is enabled and this is the internal json_tool_call, + # suppress it from tool_calls and convert arguments to text content + if ( + self.json_mode is True + and response_tool_name == RESPONSE_FORMAT_TOOL_NAME + ): + self._current_block_is_json_tool_call = True + verbose_logger.debug( + "Suppressing %s from streaming tool calls", + RESPONSE_FORMAT_TOOL_NAME, + ) + else: + self.tool_calls_index = ( + 0 + if self.tool_calls_index is None + else self.tool_calls_index + 1 + ) + tool_use = { + "id": start_obj["toolUse"]["toolUseId"], + "type": "function", + "function": { + "name": response_tool_name, + "arguments": "", + }, + "index": self.tool_calls_index, + } elif ( "reasoningContent" in start_obj and start_obj["reasoningContent"] is not None @@ -1445,19 +1464,23 @@ def _handle_converse_delta_event( if "text" in delta_obj: text = delta_obj["text"] elif "toolUse" in delta_obj: - tool_use = { - "id": None, - "type": "function", - "function": { - "name": None, - "arguments": delta_obj["toolUse"]["input"], - }, - "index": ( - self.tool_calls_index - if self.tool_calls_index is not None - else index - ), - } + if self._current_block_is_json_tool_call: + # Convert json_tool_call arguments to text content instead of tool_use + text = delta_obj["toolUse"]["input"] + else: + tool_use = { + "id": None, + "type": "function", + "function": { + "name": None, + "arguments": delta_obj["toolUse"]["input"], + }, + "index": ( + self.tool_calls_index + if self.tool_calls_index is not None + else index + ), + } elif "reasoningContent" in delta_obj: provider_specific_fields = { "reasoningContent": delta_obj["reasoningContent"], @@ -1494,6 +1517,8 @@ def _handle_converse_stop_event( ) -> Optional[ChatCompletionToolCallChunk]: """Handle stop/contentBlockIndex event in converse chunk parsing.""" tool_use: Optional[ChatCompletionToolCallChunk] = None + if self._current_block_is_json_tool_call: + return None # Don't emit tool_use for suppressed json_tool_call blocks is_empty = self.check_empty_tool_call_args() if is_empty: tool_use = { diff --git a/litellm/llms/bedrock/common_utils.py b/litellm/llms/bedrock/common_utils.py index 65d237bdbdf..4c87f6fa994 100644 --- a/litellm/llms/bedrock/common_utils.py +++ b/litellm/llms/bedrock/common_utils.py @@ -446,6 +446,29 @@ def get_bedrock_base_model(model: str) -> str: return model +def is_claude_4_5_on_bedrock(model: str) -> bool: + """ + Check if the model is a Claude 4.5 model on Bedrock. + Claude 4.5 models support prompt caching with '5m' and '1h' TTL on Bedrock. + """ + model_lower = model.lower() + claude_4_5_patterns = [ + "sonnet-4.5", + "sonnet_4.5", + "sonnet-4-5", + "sonnet_4_5", + "haiku-4.5", + "haiku_4.5", + "haiku-4-5", + "haiku_4_5", + "opus-4.5", + "opus_4.5", + "opus-4-5", + "opus_4_5", + ] + return any(pattern in model_lower for pattern in claude_4_5_patterns) + + # Import after standalone functions to avoid circular imports from litellm.llms.bedrock.count_tokens.bedrock_token_counter import BedrockTokenCounter @@ -815,21 +838,23 @@ def get_anthropic_beta_from_headers(headers: dict) -> List[str]: # If it's already a list, return it if isinstance(anthropic_beta_header, list): return anthropic_beta_header - + # Try to parse as JSON array first (e.g., '["interleaved-thinking-2025-05-14", "claude-code-20250219"]') if isinstance(anthropic_beta_header, str): anthropic_beta_header = anthropic_beta_header.strip() - if anthropic_beta_header.startswith("[") and anthropic_beta_header.endswith("]"): + if anthropic_beta_header.startswith("[") and anthropic_beta_header.endswith( + "]" + ): try: parsed = json.loads(anthropic_beta_header) if isinstance(parsed, list): return [str(beta).strip() for beta in parsed] except json.JSONDecodeError: pass # Fall through to comma-separated parsing - + # Fall back to comma-separated values return [beta.strip() for beta in anthropic_beta_header.split(",")] - + return [] diff --git a/litellm/llms/bedrock/embed/cohere_transformation.py b/litellm/llms/bedrock/embed/cohere_transformation.py index 490cd71b793..d00cb74aae0 100644 --- a/litellm/llms/bedrock/embed/cohere_transformation.py +++ b/litellm/llms/bedrock/embed/cohere_transformation.py @@ -15,7 +15,7 @@ def __init__(self) -> None: pass def get_supported_openai_params(self) -> List[str]: - return ["encoding_format"] + return ["encoding_format", "dimensions"] def map_openai_params( self, non_default_params: dict, optional_params: dict @@ -23,6 +23,8 @@ def map_openai_params( for k, v in non_default_params.items(): if k == "encoding_format": optional_params["embedding_types"] = v + elif k == "dimensions": + optional_params["output_dimension"] = v return optional_params def _is_v3_model(self, model: str) -> bool: diff --git a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py index b1c45ea83a2..19fe7d8c140 100644 --- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py +++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py @@ -12,6 +12,9 @@ import httpx +from litellm.anthropic_beta_headers_manager import ( + filter_and_transform_beta_headers, +) from litellm.llms.anthropic.common_utils import AnthropicModelInfo from litellm.llms.anthropic.experimental_pass_through.messages.transformation import ( AnthropicMessagesConfig, @@ -23,7 +26,10 @@ from litellm.llms.bedrock.chat.invoke_transformations.base_invoke_transformation import ( AmazonInvokeConfig, ) -from litellm.llms.bedrock.common_utils import get_anthropic_beta_from_headers +from litellm.llms.bedrock.common_utils import ( + get_anthropic_beta_from_headers, + is_claude_4_5_on_bedrock, +) from litellm.types.llms.anthropic import ANTHROPIC_TOOL_SEARCH_BETA_HEADER from litellm.types.llms.openai import AllMessageValues from litellm.types.router import GenericLiteLLMParams @@ -52,10 +58,6 @@ class AmazonAnthropicClaudeMessagesConfig( # Beta header patterns that are not supported by Bedrock Invoke API # These will be filtered out to prevent 400 "invalid beta flag" errors - UNSUPPORTED_BEDROCK_INVOKE_BETA_PATTERNS = [ - "advanced-tool-use", # Bedrock Invoke doesn't support advanced-tool-use beta headers - "prompt-caching-scope" - ] def __init__(self, **kwargs): BaseAnthropicMessagesConfig.__init__(self, **kwargs) @@ -116,15 +118,22 @@ def get_complete_url( ) def _remove_ttl_from_cache_control( - self, anthropic_messages_request: Dict + self, anthropic_messages_request: Dict, model: Optional[str] = None ) -> None: """ Remove `ttl` field from cache_control in messages. Bedrock doesn't support the ttl field in cache_control. + Update: Bedock supports `5m` and `1h` for Claude 4.5 models. + Args: anthropic_messages_request: The request dictionary to modify in-place + model: The model name to check if it supports ttl """ + is_claude_4_5 = False + if model: + is_claude_4_5 = self._is_claude_4_5_on_bedrock(model) + if "messages" in anthropic_messages_request: for message in anthropic_messages_request["messages"]: if isinstance(message, dict) and "content" in message: @@ -133,7 +142,14 @@ def _remove_ttl_from_cache_control( for item in content: if isinstance(item, dict) and "cache_control" in item: cache_control = item["cache_control"] - if isinstance(cache_control, dict) and "ttl" in cache_control: + if ( + isinstance(cache_control, dict) + and "ttl" in cache_control + ): + ttl = cache_control["ttl"] + if is_claude_4_5 and ttl in ["5m", "1h"]: + continue + cache_control.pop("ttl", None) def _supports_extended_thinking_on_bedrock(self, model: str) -> bool: @@ -155,10 +171,18 @@ def _supports_extended_thinking_on_bedrock(self, model: str) -> bool: # Supported models on Bedrock for extended thinking supported_patterns = [ - "opus-4.5", "opus_4.5", "opus-4-5", "opus_4_5", # Opus 4.5 - "opus-4.1", "opus_4.1", "opus-4-1", "opus_4_1", # Opus 4.1 - "opus-4", "opus_4", # Opus 4 - "sonnet-4", "sonnet_4", # Sonnet 4 + "opus-4.5", + "opus_4.5", + "opus-4-5", + "opus_4_5", # Opus 4.5 + "opus-4.1", + "opus_4.1", + "opus-4-1", + "opus_4_1", # Opus 4.1 + "opus-4", + "opus_4", # Opus 4 + "sonnet-4", + "sonnet_4", # Sonnet 4 ] return any(pattern in model_lower for pattern in supported_patterns) @@ -175,10 +199,27 @@ def _is_claude_opus_4_5(self, model: str) -> bool: """ model_lower = model.lower() opus_4_5_patterns = [ - "opus-4.5", "opus_4.5", "opus-4-5", "opus_4_5", + "opus-4.5", + "opus_4.5", + "opus-4-5", + "opus_4_5", ] return any(pattern in model_lower for pattern in opus_4_5_patterns) + def _is_claude_4_5_on_bedrock(self, model: str) -> bool: + """ + Check if the model is Claude 4.5 on Bedrock. + + Claude Sonnet 4.5, Haiku 4.5, and Opus 4.5 support 1-hour prompt caching. + + Args: + model: The model name + + Returns: + True if the model is Claude 4.5 + """ + return is_claude_4_5_on_bedrock(model) + def _supports_tool_search_on_bedrock(self, model: str) -> bool: """ Check if the model supports tool search on Bedrock. @@ -199,9 +240,15 @@ def _supports_tool_search_on_bedrock(self, model: str) -> bool: # Supported models for tool search on Bedrock supported_patterns = [ # Opus 4.5 - "opus-4.5", "opus_4.5", "opus-4-5", "opus_4_5", + "opus-4.5", + "opus_4.5", + "opus-4-5", + "opus_4_5", # Sonnet 4.5 - "sonnet-4.5", "sonnet_4.5", "sonnet-4-5", "sonnet_4_5", + "sonnet-4.5", + "sonnet_4.5", + "sonnet-4-5", + "sonnet_4_5", ] return any(pattern in model_lower for pattern in supported_patterns) @@ -228,41 +275,48 @@ def _filter_unsupported_beta_headers_for_bedrock( model: The model name beta_set: The set of beta headers to filter in-place """ - beta_headers_to_remove = set() - has_advanced_tool_use = False - - # 1. Filter out beta headers that are universally unsupported on Bedrock Invoke and track if advanced-tool-use header is present - for beta in beta_set: - for unsupported_pattern in self.UNSUPPORTED_BEDROCK_INVOKE_BETA_PATTERNS: - if unsupported_pattern in beta.lower(): - beta_headers_to_remove.add(beta) - has_advanced_tool_use = True - break - + # 1. Handle header transformations BEFORE filtering + # (advanced-tool-use -> tool-search-tool) + # This must happen before filtering because advanced-tool-use is in the unsupported list + has_advanced_tool_use = "advanced-tool-use-2025-11-20" in beta_set + if has_advanced_tool_use and self._supports_tool_search_on_bedrock(model): + beta_set.discard("advanced-tool-use-2025-11-20") + beta_set.add("tool-search-tool-2025-10-19") + beta_set.add("tool-examples-2025-10-29") + + # 2. Apply provider-level filtering using centralized JSON config + beta_list = list(beta_set) + filtered_list = filter_and_transform_beta_headers( + beta_headers=beta_list, + provider="bedrock", + ) + + # Update the set with filtered headers + beta_set.clear() + beta_set.update(filtered_list) + + # 2.1. Handle model-specific exceptions: structured-outputs is only supported on Opus 4.6 + # Re-add structured-outputs if it was in the original set and model is Opus 4.6 + model_lower = model.lower() + is_opus_4_6 = any(pattern in model_lower for pattern in ["opus-4.6", "opus_4.6", "opus-4-6", "opus_4_6"]) + if is_opus_4_6 and "structured-outputs-2025-11-13" in beta_list: + beta_set.add("structured-outputs-2025-11-13") - # 2. Filter out extended thinking headers for models that don't support them + # 3. Filter out extended thinking headers for models that don't support them extended_thinking_patterns = [ "extended-thinking", "interleaved-thinking", ] if not self._supports_extended_thinking_on_bedrock(model): + beta_headers_to_remove = set() for beta in beta_set: for pattern in extended_thinking_patterns: if pattern in beta.lower(): beta_headers_to_remove.add(beta) break - - # Remove all filtered headers - for beta in beta_headers_to_remove: - beta_set.discard(beta) - - # 3. Translate advanced-tool-use to Bedrock-specific headers for models that support tool search - # Ref: https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages-request-response.html - # Ref: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool - if has_advanced_tool_use and self._supports_tool_search_on_bedrock(model): - beta_set.add("tool-search-tool-2025-10-19") - beta_set.add("tool-examples-2025-10-29") - + + for beta in beta_headers_to_remove: + beta_set.discard(beta) def _get_tool_search_beta_header_for_bedrock( self, @@ -290,7 +344,9 @@ def _get_tool_search_beta_header_for_bedrock( input_examples_used: Whether input examples are used beta_set: The set of beta headers to modify in-place """ - if tool_search_used and not (programmatic_tool_calling_used or input_examples_used): + if tool_search_used and not ( + programmatic_tool_calling_used or input_examples_used + ): beta_set.discard(ANTHROPIC_TOOL_SEARCH_BETA_HEADER) if "opus-4" in model.lower() or "opus_4" in model.lower(): beta_set.add("tool-search-tool-2025-10-19") @@ -302,13 +358,13 @@ def _convert_output_format_to_inline_schema( ) -> None: """ Convert Anthropic output_format to inline schema in message content. - + Bedrock Invoke doesn't support the output_format parameter, so we embed the schema directly into the user message content as text instructions. - + This approach adds the schema to the last user message, instructing the model to respond in the specified JSON format. - + Args: output_format: The output_format dict with 'type' and 'schema' anthropic_messages_request: The request dict to modify in-place @@ -321,35 +377,32 @@ def _convert_output_format_to_inline_schema( schema = output_format.get("schema") if not schema: return - + # Get messages from the request messages = anthropic_messages_request.get("messages", []) if not messages: return - + # Find the last user message last_user_message_idx = None for idx in range(len(messages) - 1, -1, -1): if messages[idx].get("role") == "user": last_user_message_idx = idx break - + if last_user_message_idx is None: return - + last_user_message = messages[last_user_message_idx] content = last_user_message.get("content", []) - + # Ensure content is a list if isinstance(content, str): content = [{"type": "text", "text": content}] last_user_message["content"] = content - + # Add schema as text content to the message - schema_text = { - "type": "text", - "text": json.dumps(schema) - } + schema_text = {"type": "text", "text": json.dumps(schema)} content.append(schema_text) def transform_anthropic_messages_request( @@ -374,9 +427,9 @@ def transform_anthropic_messages_request( # 1. anthropic_version is required for all claude models if "anthropic_version" not in anthropic_messages_request: - anthropic_messages_request["anthropic_version"] = ( - self.DEFAULT_BEDROCK_ANTHROPIC_API_VERSION - ) + anthropic_messages_request[ + "anthropic_version" + ] = self.DEFAULT_BEDROCK_ANTHROPIC_API_VERSION # 2. `stream` is not allowed in request body for bedrock invoke if "stream" in anthropic_messages_request: @@ -386,8 +439,10 @@ def transform_anthropic_messages_request( if "model" in anthropic_messages_request: anthropic_messages_request.pop("model", None) - # 4. Remove `ttl` field from cache_control in messages (Bedrock doesn't support it) - self._remove_ttl_from_cache_control(anthropic_messages_request) + # 4. Remove `ttl` field from cache_control in messages (Bedrock doesn't support it for older models) + self._remove_ttl_from_cache_control( + anthropic_messages_request=anthropic_messages_request, model=model + ) # 5. Convert `output_format` to inline schema (Bedrock invoke doesn't support output_format) output_format = anthropic_messages_request.pop("output_format", None) @@ -396,14 +451,14 @@ def transform_anthropic_messages_request( output_format=output_format, anthropic_messages_request=anthropic_messages_request, ) - + # 6. AUTO-INJECT beta headers based on features used anthropic_model_info = AnthropicModelInfo() tools = anthropic_messages_optional_request_params.get("tools") messages_typed = cast(List[AllMessageValues], messages) tool_search_used = anthropic_model_info.is_tool_search_used(tools) - programmatic_tool_calling_used = anthropic_model_info.is_programmatic_tool_calling_used( - tools + programmatic_tool_calling_used = ( + anthropic_model_info.is_programmatic_tool_calling_used(tools) ) input_examples_used = anthropic_model_info.is_input_examples_used(tools) @@ -436,8 +491,7 @@ def transform_anthropic_messages_request( if beta_set: anthropic_messages_request["anthropic_beta"] = list(beta_set) - - + return anthropic_messages_request def get_async_streaming_response_iterator( @@ -455,7 +509,7 @@ def get_async_streaming_response_iterator( ) # Convert decoded Bedrock events to Server-Sent Events expected by Anthropic clients. return self.bedrock_sse_wrapper( - completion_stream=completion_stream, + completion_stream=completion_stream, litellm_logging_obj=litellm_logging_obj, request_body=request_body, ) @@ -474,14 +528,14 @@ async def bedrock_sse_wrapper( from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import ( BaseAnthropicMessagesStreamingIterator, ) + handler = BaseAnthropicMessagesStreamingIterator( litellm_logging_obj=litellm_logging_obj, request_body=request_body, ) - + async for chunk in handler.async_sse_wrapper(completion_stream): yield chunk - class AmazonAnthropicClaudeMessagesStreamDecoder(AWSEventStreamDecoder): diff --git a/litellm/llms/bedrock/realtime/handler.py b/litellm/llms/bedrock/realtime/handler.py new file mode 100644 index 00000000000..9b6a80f4a2f --- /dev/null +++ b/litellm/llms/bedrock/realtime/handler.py @@ -0,0 +1,307 @@ +""" +This file contains the handler for AWS Bedrock Nova Sonic realtime API. + +This uses aws_sdk_bedrock_runtime for bidirectional streaming with Nova Sonic. +""" + +import asyncio +import json +from typing import Any, Optional + +from litellm._logging import verbose_proxy_logger +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging + +from ..base_aws_llm import BaseAWSLLM +from .transformation import BedrockRealtimeConfig + + +class BedrockRealtime(BaseAWSLLM): + """Handler for Bedrock Nova Sonic realtime speech-to-speech API.""" + + def __init__(self): + super().__init__() + + async def async_realtime( + self, + model: str, + websocket: Any, + logging_obj: LiteLLMLogging, + api_base: Optional[str] = None, + api_key: Optional[str] = None, + timeout: Optional[float] = None, + aws_region_name: Optional[str] = None, + aws_access_key_id: Optional[str] = None, + aws_secret_access_key: Optional[str] = None, + aws_session_token: Optional[str] = None, + aws_role_name: Optional[str] = None, + aws_session_name: Optional[str] = None, + aws_profile_name: Optional[str] = None, + aws_web_identity_token: Optional[str] = None, + aws_sts_endpoint: Optional[str] = None, + aws_bedrock_runtime_endpoint: Optional[str] = None, + aws_external_id: Optional[str] = None, + **kwargs, + ): + """ + Establish bidirectional streaming connection with Bedrock Nova Sonic. + + Args: + model: Model ID (e.g., 'amazon.nova-sonic-v1:0') + websocket: Client WebSocket connection + logging_obj: LiteLLM logging object + aws_region_name: AWS region + Various AWS authentication parameters + """ + try: + from aws_sdk_bedrock_runtime.client import ( + BedrockRuntimeClient, + InvokeModelWithBidirectionalStreamOperationInput, + ) + from aws_sdk_bedrock_runtime.config import Config + from smithy_aws_core.identity.environment import ( + EnvironmentCredentialsResolver, + ) + except ImportError: + raise ImportError( + "Missing aws_sdk_bedrock_runtime. Install with: pip install aws-sdk-bedrock-runtime" + ) + + # Get AWS region + if aws_region_name is None: + optional_params = { + "aws_region_name": aws_region_name, + } + aws_region_name = self._get_aws_region_name(optional_params, model) + + # Get endpoint URL + if api_base is not None: + endpoint_uri = api_base + elif aws_bedrock_runtime_endpoint is not None: + endpoint_uri = aws_bedrock_runtime_endpoint + else: + endpoint_uri = f"https://bedrock-runtime.{aws_region_name}.amazonaws.com" + + verbose_proxy_logger.debug( + f"Bedrock Realtime: Connecting to {endpoint_uri} with model {model}" + ) + + # Initialize Bedrock client with aws_sdk_bedrock_runtime + config = Config( + endpoint_uri=endpoint_uri, + region=aws_region_name, + aws_credentials_identity_resolver=EnvironmentCredentialsResolver(), + ) + bedrock_client = BedrockRuntimeClient(config=config) + + transformation_config = BedrockRealtimeConfig() + + try: + # Initialize the bidirectional stream + bedrock_stream = await bedrock_client.invoke_model_with_bidirectional_stream( + InvokeModelWithBidirectionalStreamOperationInput(model_id=model) + ) + + verbose_proxy_logger.debug( + "Bedrock Realtime: Bidirectional stream established" + ) + + # Track state for transformation + session_state = { + "current_output_item_id": None, + "current_response_id": None, + "current_conversation_id": None, + "current_delta_chunks": None, + "current_item_chunks": None, + "current_delta_type": None, + "session_configuration_request": None, + } + + # Create tasks for bidirectional forwarding + client_to_bedrock_task = asyncio.create_task( + self._forward_client_to_bedrock( + websocket, + bedrock_stream, + transformation_config, + model, + session_state, + ) + ) + + bedrock_to_client_task = asyncio.create_task( + self._forward_bedrock_to_client( + bedrock_stream, + websocket, + transformation_config, + model, + logging_obj, + session_state, + ) + ) + + # Wait for both tasks to complete + await asyncio.gather( + client_to_bedrock_task, + bedrock_to_client_task, + return_exceptions=True, + ) + + except Exception as e: + verbose_proxy_logger.exception( + f"Error in BedrockRealtime.async_realtime: {e}" + ) + try: + await websocket.close(code=1011, reason=f"Internal error: {str(e)}") + except Exception: + pass + raise + + async def _forward_client_to_bedrock( + self, + client_ws: Any, + bedrock_stream: Any, + transformation_config: BedrockRealtimeConfig, + model: str, + session_state: dict, + ): + """Forward messages from client WebSocket to Bedrock stream.""" + try: + from aws_sdk_bedrock_runtime.models import ( + BidirectionalInputPayloadPart, + InvokeModelWithBidirectionalStreamInputChunk, + ) + + while True: + # Receive message from client + message = await client_ws.receive_text() + verbose_proxy_logger.debug( + f"Bedrock Realtime: Received from client: {message[:200]}" + ) + + # Transform OpenAI format to Bedrock format + transformed_messages = transformation_config.transform_realtime_request( + message=message, + model=model, + session_configuration_request=session_state.get( + "session_configuration_request" + ), + ) + + # Send transformed messages to Bedrock + for bedrock_message in transformed_messages: + event = InvokeModelWithBidirectionalStreamInputChunk( + value=BidirectionalInputPayloadPart( + bytes_=bedrock_message.encode("utf-8") + ) + ) + await bedrock_stream.input_stream.send(event) + verbose_proxy_logger.debug( + f"Bedrock Realtime: Sent to Bedrock: {bedrock_message[:200]}" + ) + + except Exception as e: + verbose_proxy_logger.debug( + f"Client to Bedrock forwarding ended: {e}", exc_info=True + ) + # Close the Bedrock stream input + try: + await bedrock_stream.input_stream.close() + except Exception: + pass + + async def _forward_bedrock_to_client( + self, + bedrock_stream: Any, + client_ws: Any, + transformation_config: BedrockRealtimeConfig, + model: str, + logging_obj: LiteLLMLogging, + session_state: dict, + ): + """Forward messages from Bedrock stream to client WebSocket.""" + try: + while True: + # Receive from Bedrock + output = await bedrock_stream.await_output() + result = await output[1].receive() + + if result.value and result.value.bytes_: + bedrock_response = result.value.bytes_.decode("utf-8") + verbose_proxy_logger.debug( + f"Bedrock Realtime: Received from Bedrock: {bedrock_response[:200]}" + ) + + # Transform Bedrock format to OpenAI format + from litellm.types.realtime import RealtimeResponseTransformInput + + realtime_response_transform_input: RealtimeResponseTransformInput = { + "current_output_item_id": session_state.get( + "current_output_item_id" + ), + "current_response_id": session_state.get("current_response_id"), + "current_conversation_id": session_state.get( + "current_conversation_id" + ), + "current_delta_chunks": session_state.get( + "current_delta_chunks" + ), + "current_item_chunks": session_state.get("current_item_chunks"), + "current_delta_type": session_state.get("current_delta_type"), + "session_configuration_request": session_state.get( + "session_configuration_request" + ), + } + + transformed_response = ( + transformation_config.transform_realtime_response( + message=bedrock_response, + model=model, + logging_obj=logging_obj, + realtime_response_transform_input=realtime_response_transform_input, + ) + ) + + # Update session state + session_state.update( + { + "current_output_item_id": transformed_response.get( + "current_output_item_id" + ), + "current_response_id": transformed_response.get( + "current_response_id" + ), + "current_conversation_id": transformed_response.get( + "current_conversation_id" + ), + "current_delta_chunks": transformed_response.get( + "current_delta_chunks" + ), + "current_item_chunks": transformed_response.get( + "current_item_chunks" + ), + "current_delta_type": transformed_response.get( + "current_delta_type" + ), + "session_configuration_request": transformed_response.get( + "session_configuration_request" + ), + } + ) + + # Send transformed messages to client + openai_messages = transformed_response.get("response", []) + for openai_message in openai_messages: + message_json = json.dumps(openai_message) + await client_ws.send_text(message_json) + verbose_proxy_logger.debug( + f"Bedrock Realtime: Sent to client: {message_json[:200]}" + ) + + except Exception as e: + verbose_proxy_logger.debug( + f"Bedrock to client forwarding ended: {e}", exc_info=True + ) + # Close the client WebSocket + try: + await client_ws.close() + except Exception: + pass diff --git a/litellm/llms/bedrock/realtime/transformation.py b/litellm/llms/bedrock/realtime/transformation.py new file mode 100644 index 00000000000..1dde1b47fe3 --- /dev/null +++ b/litellm/llms/bedrock/realtime/transformation.py @@ -0,0 +1,1156 @@ +""" +This file contains the transformation logic for Bedrock Nova Sonic realtime API. + +Transforms between OpenAI Realtime API format and Bedrock Nova Sonic format. +""" + +import json +import uuid as uuid_lib +from typing import Any, List, Optional, Union + +from litellm._logging import verbose_logger +from litellm._uuid import uuid +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.base_llm.realtime.transformation import BaseRealtimeConfig +from litellm.types.llms.openai import ( + OpenAIRealtimeContentPartDone, + OpenAIRealtimeDoneEvent, + OpenAIRealtimeEvents, + OpenAIRealtimeOutputItemDone, + OpenAIRealtimeResponseAudioDone, + OpenAIRealtimeResponseContentPartAdded, + OpenAIRealtimeResponseDelta, + OpenAIRealtimeResponseDoneObject, + OpenAIRealtimeResponseTextDone, + OpenAIRealtimeStreamResponseBaseObject, + OpenAIRealtimeStreamResponseOutputItemAdded, + OpenAIRealtimeStreamSession, + OpenAIRealtimeStreamSessionEvents, +) +from litellm.types.realtime import ( + ALL_DELTA_TYPES, + RealtimeResponseTransformInput, + RealtimeResponseTypedDict, +) +from litellm.utils import get_empty_usage + + +class BedrockRealtimeConfig(BaseRealtimeConfig): + """Configuration for Bedrock Nova Sonic realtime transformations.""" + + def __init__(self): + # Track session state + self.prompt_name = str(uuid_lib.uuid4()) + self.content_name = str(uuid_lib.uuid4()) + self.audio_content_name = str(uuid_lib.uuid4()) + + # Default configuration values + # Inference configuration + self.max_tokens = 1024 + self.top_p = 0.9 + self.temperature = 0.7 + + # Audio output configuration + self.output_sample_rate_hertz = 24000 + self.output_sample_size_bits = 16 + self.output_channel_count = 1 + self.voice_id = "matthew" + self.output_encoding = "base64" + self.output_audio_type = "SPEECH" + self.output_media_type = "audio/lpcm" + + # Audio input configuration + self.input_sample_rate_hertz = 16000 + self.input_sample_size_bits = 16 + self.input_channel_count = 1 + self.input_encoding = "base64" + self.input_audio_type = "SPEECH" + self.input_media_type = "audio/lpcm" + + # Text configuration + self.text_media_type = "text/plain" + + def validate_environment( + self, headers: dict, model: str, api_key: Optional[str] = None + ) -> dict: + """Validate environment - no special validation needed for Bedrock.""" + return headers + + def get_complete_url( + self, api_base: Optional[str], model: str, api_key: Optional[str] = None + ) -> str: + """Get complete URL - handled by aws_sdk_bedrock_runtime.""" + return api_base or "" + + def requires_session_configuration(self) -> bool: + """Bedrock requires session configuration.""" + return True + + def session_configuration_request(self, model: str, tools: Optional[List[dict]] = None) -> str: + """ + Create initial session configuration for Bedrock Nova Sonic. + + Args: + model: Model ID + tools: Optional list of tool definitions + + Returns JSON string with session start and prompt start events. + """ + session_start = { + "event": { + "sessionStart": { + "inferenceConfiguration": { + "maxTokens": self.max_tokens, + "topP": self.top_p, + "temperature": self.temperature, + } + } + } + } + + prompt_start_config = { + "promptName": self.prompt_name, + "textOutputConfiguration": {"mediaType": self.text_media_type}, + "audioOutputConfiguration": { + "mediaType": self.output_media_type, + "sampleRateHertz": self.output_sample_rate_hertz, + "sampleSizeBits": self.output_sample_size_bits, + "channelCount": self.output_channel_count, + "voiceId": self.voice_id, + "encoding": self.output_encoding, + "audioType": self.output_audio_type, + }, + } + + # Add tool configuration if tools are provided + if tools: + prompt_start_config["toolUseOutputConfiguration"] = { + "mediaType": "application/json" + } + prompt_start_config["toolConfiguration"] = { + "tools": self._transform_tools_to_bedrock_format(tools) + } + + prompt_start = {"event": {"promptStart": prompt_start_config}} + + # Return as a marker that we've sent the configuration + return json.dumps( + {"session_start": session_start, "prompt_start": prompt_start} + ) + + def _transform_tools_to_bedrock_format(self, tools: List[dict]) -> List[dict]: + """ + Transform OpenAI tool format to Bedrock tool format. + + Args: + tools: List of OpenAI format tools + + Returns: + List of Bedrock format tools + """ + bedrock_tools = [] + for tool in tools: + if tool.get("type") == "function": + function = tool.get("function", {}) + bedrock_tool = { + "toolSpec": { + "name": function.get("name", ""), + "description": function.get("description", ""), + "inputSchema": { + "json": json.dumps(function.get("parameters", {})) + } + } + } + bedrock_tools.append(bedrock_tool) + return bedrock_tools + + def _map_audio_format_to_sample_rate(self, audio_format: str, is_output: bool = True) -> int: + """ + Map OpenAI audio format to sample rate. + + Args: + audio_format: OpenAI audio format (pcm16, g711_ulaw, g711_alaw) + is_output: Whether this is for output (True) or input (False) + + Returns: + Sample rate in Hz + """ + # OpenAI uses 24kHz for output and can vary for input + # Bedrock Nova Sonic uses 24kHz for output and 16kHz for input by default + if audio_format == "pcm16": + return 24000 if is_output else 16000 + elif audio_format in ["g711_ulaw", "g711_alaw"]: + return 8000 # G.711 typically uses 8kHz + return 24000 if is_output else 16000 + + def transform_session_update_event(self, json_message: dict) -> List[str]: + """ + Transform session.update event to Bedrock session configuration. + + Args: + json_message: OpenAI session.update message + + Returns: + List of Bedrock format messages (JSON strings) + """ + verbose_logger.debug("Handling session.update") + messages: List[str] = [] + + session_config = json_message.get("session", {}) + + # Update inference configuration from session if provided + if "max_response_output_tokens" in session_config: + self.max_tokens = session_config["max_response_output_tokens"] + if "temperature" in session_config: + self.temperature = session_config["temperature"] + + # Update audio output configuration from session if provided + if "voice" in session_config: + self.voice_id = session_config["voice"] + if "output_audio_format" in session_config: + output_format = session_config["output_audio_format"] + self.output_sample_rate_hertz = self._map_audio_format_to_sample_rate( + output_format, is_output=True + ) + + # Update audio input configuration from session if provided + if "input_audio_format" in session_config: + input_format = session_config["input_audio_format"] + self.input_sample_rate_hertz = self._map_audio_format_to_sample_rate( + input_format, is_output=False + ) + + # Allow direct override of sample rates if provided (custom extension) + if "output_sample_rate_hertz" in session_config: + self.output_sample_rate_hertz = session_config["output_sample_rate_hertz"] + if "input_sample_rate_hertz" in session_config: + self.input_sample_rate_hertz = session_config["input_sample_rate_hertz"] + + # Send session start + session_start = { + "event": { + "sessionStart": { + "inferenceConfiguration": { + "maxTokens": self.max_tokens, + "topP": self.top_p, + "temperature": self.temperature, + } + } + } + } + messages.append(json.dumps(session_start)) + + # Send prompt start + prompt_start_config = { + "promptName": self.prompt_name, + "textOutputConfiguration": {"mediaType": self.text_media_type}, + "audioOutputConfiguration": { + "mediaType": self.output_media_type, + "sampleRateHertz": self.output_sample_rate_hertz, + "sampleSizeBits": self.output_sample_size_bits, + "channelCount": self.output_channel_count, + "voiceId": self.voice_id, + "encoding": self.output_encoding, + "audioType": self.output_audio_type, + }, + } + + # Add tool configuration if tools are provided + tools = session_config.get("tools") + if tools: + prompt_start_config["toolUseOutputConfiguration"] = { + "mediaType": "application/json" + } + prompt_start_config["toolConfiguration"] = { + "tools": self._transform_tools_to_bedrock_format(tools) + } + + prompt_start = {"event": {"promptStart": prompt_start_config}} + messages.append(json.dumps(prompt_start)) + + # Send system prompt if provided + instructions = session_config.get("instructions") + if instructions: + text_content_name = str(uuid_lib.uuid4()) + + # Content start + text_content_start = { + "event": { + "contentStart": { + "promptName": self.prompt_name, + "contentName": text_content_name, + "type": "TEXT", + "interactive": False, + "role": "SYSTEM", + "textInputConfiguration": {"mediaType": self.text_media_type}, + } + } + } + messages.append(json.dumps(text_content_start)) + + # Text input + text_input = { + "event": { + "textInput": { + "promptName": self.prompt_name, + "contentName": text_content_name, + "content": instructions, + } + } + } + messages.append(json.dumps(text_input)) + + # Content end + text_content_end = { + "event": { + "contentEnd": { + "promptName": self.prompt_name, + "contentName": text_content_name, + } + } + } + messages.append(json.dumps(text_content_end)) + + return messages + + def transform_input_audio_buffer_append_event(self, json_message: dict) -> List[str]: + """ + Transform input_audio_buffer.append event to Bedrock audio input. + + Args: + json_message: OpenAI input_audio_buffer.append message + + Returns: + List of Bedrock format messages (JSON strings) + """ + verbose_logger.debug("Handling input_audio_buffer.append") + messages: List[str] = [] + + # Check if we need to start audio content + if not hasattr(self, "_audio_content_started"): + audio_content_start = { + "event": { + "contentStart": { + "promptName": self.prompt_name, + "contentName": self.audio_content_name, + "type": "AUDIO", + "interactive": True, + "role": "USER", + "audioInputConfiguration": { + "mediaType": self.input_media_type, + "sampleRateHertz": self.input_sample_rate_hertz, + "sampleSizeBits": self.input_sample_size_bits, + "channelCount": self.input_channel_count, + "audioType": self.input_audio_type, + "encoding": self.input_encoding, + }, + } + } + } + messages.append(json.dumps(audio_content_start)) + self._audio_content_started = True + + # Send audio chunk + audio_data = json_message.get("audio", "") + audio_event = { + "event": { + "audioInput": { + "promptName": self.prompt_name, + "contentName": self.audio_content_name, + "content": audio_data, + } + } + } + messages.append(json.dumps(audio_event)) + + return messages + + def transform_input_audio_buffer_commit_event(self, json_message: dict) -> List[str]: + """ + Transform input_audio_buffer.commit event to Bedrock audio content end. + + Args: + json_message: OpenAI input_audio_buffer.commit message + + Returns: + List of Bedrock format messages (JSON strings) + """ + verbose_logger.debug("Handling input_audio_buffer.commit") + messages: List[str] = [] + + if hasattr(self, "_audio_content_started"): + audio_content_end = { + "event": { + "contentEnd": { + "promptName": self.prompt_name, + "contentName": self.audio_content_name, + } + } + } + messages.append(json.dumps(audio_content_end)) + delattr(self, "_audio_content_started") + + return messages + + def transform_conversation_item_create_event(self, json_message: dict) -> List[str]: + """ + Transform conversation.item.create event to Bedrock text input or tool result. + + Args: + json_message: OpenAI conversation.item.create message + + Returns: + List of Bedrock format messages (JSON strings) + """ + verbose_logger.debug("Handling conversation.item.create") + messages: List[str] = [] + + item = json_message.get("item", {}) + item_type = item.get("type") + + # Handle tool result + if item_type == "function_call_output": + return self.transform_conversation_item_create_tool_result_event(json_message) + + # Handle regular message + if item_type == "message": + content = item.get("content", []) + for content_part in content: + if content_part.get("type") == "input_text": + text_content_name = str(uuid_lib.uuid4()) + + # Content start + text_content_start = { + "event": { + "contentStart": { + "promptName": self.prompt_name, + "contentName": text_content_name, + "type": "TEXT", + "interactive": True, + "role": "USER", + "textInputConfiguration": { + "mediaType": self.text_media_type + }, + } + } + } + messages.append(json.dumps(text_content_start)) + + # Text input + text_input = { + "event": { + "textInput": { + "promptName": self.prompt_name, + "contentName": text_content_name, + "content": content_part.get("text", ""), + } + } + } + messages.append(json.dumps(text_input)) + + # Content end + text_content_end = { + "event": { + "contentEnd": { + "promptName": self.prompt_name, + "contentName": text_content_name, + } + } + } + messages.append(json.dumps(text_content_end)) + + return messages + + def transform_response_create_event(self, json_message: dict) -> List[str]: + """ + Transform response.create event to Bedrock format. + + Args: + json_message: OpenAI response.create message + + Returns: + List of Bedrock format messages (JSON strings) + """ + verbose_logger.debug("Handling response.create") + # Bedrock starts generating automatically, no explicit trigger needed + return [] + + def transform_response_cancel_event(self, json_message: dict) -> List[str]: + """ + Transform response.cancel event to Bedrock format. + + Args: + json_message: OpenAI response.cancel message + + Returns: + List of Bedrock format messages (JSON strings) + """ + verbose_logger.debug("Handling response.cancel") + # Send interrupt signal if needed + return [] + + def transform_realtime_request( + self, + message: str, + model: str, + session_configuration_request: Optional[str] = None, + ) -> List[str]: + """ + Transform OpenAI realtime request to Bedrock Nova Sonic format. + + Args: + message: OpenAI format message (JSON string) + model: Model ID + session_configuration_request: Previous session config + + Returns: + List of Bedrock format messages (JSON strings) + """ + try: + json_message = json.loads(message) + except json.JSONDecodeError: + verbose_logger.warning(f"Invalid JSON message: {message[:200]}") + return [] + + message_type = json_message.get("type") + + # Route to appropriate transformation method + if message_type == "session.update": + return self.transform_session_update_event(json_message) + elif message_type == "input_audio_buffer.append": + return self.transform_input_audio_buffer_append_event(json_message) + elif message_type == "input_audio_buffer.commit": + return self.transform_input_audio_buffer_commit_event(json_message) + elif message_type == "conversation.item.create": + return self.transform_conversation_item_create_event(json_message) + elif message_type == "response.create": + return self.transform_response_create_event(json_message) + elif message_type == "response.cancel": + return self.transform_response_cancel_event(json_message) + else: + verbose_logger.warning(f"Unknown message type: {message_type}") + return [] + + def transform_session_start_event( + self, + event: dict, + model: str, + logging_obj: LiteLLMLoggingObj, + ) -> OpenAIRealtimeStreamSessionEvents: + """ + Transform Bedrock sessionStart event to OpenAI session.created. + + Args: + event: Bedrock sessionStart event + model: Model ID + logging_obj: Logging object + + Returns: + OpenAI session.created event + """ + verbose_logger.debug("Handling sessionStart") + + session = OpenAIRealtimeStreamSession( + id=logging_obj.litellm_trace_id, + modalities=["text", "audio"], + ) + if model is not None and isinstance(model, str): + session["model"] = model + + return OpenAIRealtimeStreamSessionEvents( + type="session.created", + session=session, + event_id=str(uuid.uuid4()), + ) + + def transform_content_start_event( + self, + event: dict, + current_response_id: Optional[str], + current_output_item_id: Optional[str], + current_conversation_id: Optional[str], + ) -> tuple[ + List[OpenAIRealtimeEvents], + Optional[str], + Optional[str], + Optional[str], + Optional[ALL_DELTA_TYPES], + ]: + """ + Transform Bedrock contentStart event to OpenAI response events. + + Args: + event: Bedrock contentStart event + current_response_id: Current response ID + current_output_item_id: Current output item ID + current_conversation_id: Current conversation ID + + Returns: + Tuple of (events, response_id, output_item_id, conversation_id, delta_type) + """ + content_start = event["contentStart"] + role = content_start.get("role") + + if role != "ASSISTANT": + return [], current_response_id, current_output_item_id, current_conversation_id, None + + verbose_logger.debug("Handling ASSISTANT contentStart") + + # Initialize IDs if needed + if not current_response_id: + current_response_id = f"resp_{uuid.uuid4()}" + if not current_output_item_id: + current_output_item_id = f"item_{uuid.uuid4()}" + if not current_conversation_id: + current_conversation_id = f"conv_{uuid.uuid4()}" + + # Determine content type + content_type = content_start.get("type", "TEXT") + current_delta_type: ALL_DELTA_TYPES = "text" if content_type == "TEXT" else "audio" + + returned_messages: List[OpenAIRealtimeEvents] = [] + + # Send response.created + response_created = OpenAIRealtimeStreamResponseBaseObject( + type="response.created", + event_id=f"event_{uuid.uuid4()}", + response={ + "object": "realtime.response", + "id": current_response_id, + "status": "in_progress", + "output": [], + "conversation_id": current_conversation_id, + }, + ) + returned_messages.append(response_created) + + # Send response.output_item.added + output_item_added = OpenAIRealtimeStreamResponseOutputItemAdded( + type="response.output_item.added", + response_id=current_response_id, + output_index=0, + item={ + "id": current_output_item_id, + "object": "realtime.item", + "type": "message", + "status": "in_progress", + "role": "assistant", + "content": [], + }, + ) + returned_messages.append(output_item_added) + + # Send response.content_part.added + content_part_added = OpenAIRealtimeResponseContentPartAdded( + type="response.content_part.added", + content_index=0, + output_index=0, + event_id=f"event_{uuid.uuid4()}", + item_id=current_output_item_id, + part=( + {"type": "text", "text": ""} + if current_delta_type == "text" + else {"type": "audio", "transcript": ""} + ), + response_id=current_response_id, + ) + returned_messages.append(content_part_added) + + return ( + returned_messages, + current_response_id, + current_output_item_id, + current_conversation_id, + current_delta_type, + ) + + def transform_text_output_event( + self, + event: dict, + current_output_item_id: Optional[str], + current_response_id: Optional[str], + current_delta_chunks: Optional[List[OpenAIRealtimeResponseDelta]], + ) -> tuple[List[OpenAIRealtimeEvents], Optional[List[OpenAIRealtimeResponseDelta]]]: + """ + Transform Bedrock textOutput event to OpenAI response.text.delta. + + Args: + event: Bedrock textOutput event + current_output_item_id: Current output item ID + current_response_id: Current response ID + current_delta_chunks: Current delta chunks + + Returns: + Tuple of (events, updated_delta_chunks) + """ + verbose_logger.debug("Handling textOutput") + text_content = event["textOutput"].get("content", "") + + if not current_output_item_id or not current_response_id: + return [], current_delta_chunks + + text_delta = OpenAIRealtimeResponseDelta( + type="response.text.delta", + content_index=0, + event_id=f"event_{uuid.uuid4()}", + item_id=current_output_item_id, + output_index=0, + response_id=current_response_id, + delta=text_content, + ) + + # Track delta chunks + if current_delta_chunks is None: + current_delta_chunks = [] + current_delta_chunks.append(text_delta) + + return [text_delta], current_delta_chunks + + def transform_audio_output_event( + self, + event: dict, + current_output_item_id: Optional[str], + current_response_id: Optional[str], + ) -> List[OpenAIRealtimeEvents]: + """ + Transform Bedrock audioOutput event to OpenAI response.audio.delta. + + Args: + event: Bedrock audioOutput event + current_output_item_id: Current output item ID + current_response_id: Current response ID + + Returns: + List of OpenAI events + """ + verbose_logger.debug("Handling audioOutput") + audio_content = event["audioOutput"].get("content", "") + + if not current_output_item_id or not current_response_id: + return [] + + audio_delta = OpenAIRealtimeResponseDelta( + type="response.audio.delta", + content_index=0, + event_id=f"event_{uuid.uuid4()}", + item_id=current_output_item_id, + output_index=0, + response_id=current_response_id, + delta=audio_content, + ) + + return [audio_delta] + + def transform_content_end_event( + self, + event: dict, + current_output_item_id: Optional[str], + current_response_id: Optional[str], + current_delta_type: Optional[str], + current_delta_chunks: Optional[List[OpenAIRealtimeResponseDelta]], + ) -> tuple[List[OpenAIRealtimeEvents], Optional[List[OpenAIRealtimeResponseDelta]]]: + """ + Transform Bedrock contentEnd event to OpenAI response done events. + + Args: + event: Bedrock contentEnd event + current_output_item_id: Current output item ID + current_response_id: Current response ID + current_delta_type: Current delta type (text or audio) + current_delta_chunks: Current delta chunks + + Returns: + Tuple of (events, reset_delta_chunks) + """ + content_end = event["contentEnd"] + verbose_logger.debug(f"Handling contentEnd: {content_end}") + + if not current_output_item_id or not current_response_id: + return [], current_delta_chunks + + returned_messages: List[OpenAIRealtimeEvents] = [] + + # Send appropriate done event based on type + if current_delta_type == "text": + # Accumulate text + accumulated_text = "" + if current_delta_chunks: + accumulated_text = "".join( + [chunk.get("delta", "") for chunk in current_delta_chunks] + ) + + text_done = OpenAIRealtimeResponseTextDone( + type="response.text.done", + content_index=0, + event_id=f"event_{uuid.uuid4()}", + item_id=current_output_item_id, + output_index=0, + response_id=current_response_id, + text=accumulated_text, + ) + returned_messages.append(text_done) + + # Send content_part.done + content_part_done = OpenAIRealtimeContentPartDone( + type="response.content_part.done", + content_index=0, + event_id=f"event_{uuid.uuid4()}", + item_id=current_output_item_id, + output_index=0, + part={"type": "text", "text": accumulated_text}, + response_id=current_response_id, + ) + returned_messages.append(content_part_done) + + elif current_delta_type == "audio": + audio_done = OpenAIRealtimeResponseAudioDone( + type="response.audio.done", + content_index=0, + event_id=f"event_{uuid.uuid4()}", + item_id=current_output_item_id, + output_index=0, + response_id=current_response_id, + ) + returned_messages.append(audio_done) + + # Send content_part.done + content_part_done = OpenAIRealtimeContentPartDone( + type="response.content_part.done", + content_index=0, + event_id=f"event_{uuid.uuid4()}", + item_id=current_output_item_id, + output_index=0, + part={"type": "audio", "transcript": ""}, + response_id=current_response_id, + ) + returned_messages.append(content_part_done) + + # Send output_item.done + output_item_done = OpenAIRealtimeOutputItemDone( + type="response.output_item.done", + event_id=f"event_{uuid.uuid4()}", + output_index=0, + response_id=current_response_id, + item={ + "id": current_output_item_id, + "object": "realtime.item", + "type": "message", + "status": "completed", + "role": "assistant", + "content": [], + }, + ) + returned_messages.append(output_item_done) + + # Reset delta chunks + return returned_messages, None + + def transform_prompt_end_event( + self, + event: dict, + current_response_id: Optional[str], + current_conversation_id: Optional[str], + ) -> tuple[List[OpenAIRealtimeEvents], Optional[str], Optional[str], Optional[ALL_DELTA_TYPES]]: + """ + Transform Bedrock promptEnd event to OpenAI response.done. + + Args: + event: Bedrock promptEnd event + current_response_id: Current response ID + current_conversation_id: Current conversation ID + + Returns: + Tuple of (events, reset_output_item_id, reset_response_id, reset_delta_type) + """ + verbose_logger.debug("Handling promptEnd") + + if not current_response_id or not current_conversation_id: + return [], None, None, None + + usage_obj = get_empty_usage() + response_done = OpenAIRealtimeDoneEvent( + type="response.done", + event_id=f"event_{uuid.uuid4()}", + response=OpenAIRealtimeResponseDoneObject( + object="realtime.response", + id=current_response_id, + status="completed", + output=[], + conversation_id=current_conversation_id, + usage={ + "prompt_tokens": usage_obj.prompt_tokens, + "completion_tokens": usage_obj.completion_tokens, + "total_tokens": usage_obj.total_tokens, + }, + ), + ) + + # Reset state for next response + return [response_done], None, None, None + + def transform_tool_use_event( + self, + event: dict, + current_output_item_id: Optional[str], + current_response_id: Optional[str], + ) -> tuple[List[OpenAIRealtimeEvents], str, str]: + """ + Transform Bedrock toolUse event to OpenAI format. + + Args: + event: Bedrock toolUse event + current_output_item_id: Current output item ID + current_response_id: Current response ID + + Returns: + Tuple of (events, tool_call_id, tool_name) for tracking + """ + verbose_logger.debug("Handling toolUse") + tool_use = event["toolUse"] + + if not current_output_item_id or not current_response_id: + return [], "", "" + + # Parse the tool input + tool_input = {} + if "input" in tool_use: + try: + tool_input = json.loads(tool_use["input"]) if isinstance(tool_use["input"], str) else tool_use["input"] + except json.JSONDecodeError: + tool_input = {} + + tool_call_id = tool_use.get("toolUseId", "") + tool_name = tool_use.get("toolName", "") + + # Create a function call arguments done event + # This is a custom event format that matches what clients expect + from typing import cast + function_call_event: dict[str, Any] = { + "type": "response.function_call_arguments.done", + "event_id": f"event_{uuid.uuid4()}", + "response_id": current_response_id, + "item_id": current_output_item_id, + "output_index": 0, + "call_id": tool_call_id, + "name": tool_name, + "arguments": json.dumps(tool_input), + } + + return [cast(OpenAIRealtimeEvents, function_call_event)], tool_call_id, tool_name + + def transform_conversation_item_create_tool_result_event(self, json_message: dict) -> List[str]: + """ + Transform conversation.item.create with tool result to Bedrock format. + + Args: + json_message: OpenAI conversation.item.create message with tool result + + Returns: + List of Bedrock format messages (JSON strings) + """ + verbose_logger.debug("Handling conversation.item.create for tool result") + messages: List[str] = [] + + item = json_message.get("item", {}) + if item.get("type") == "function_call_output": + tool_content_name = str(uuid_lib.uuid4()) + call_id = item.get("call_id", "") + output = item.get("output", "") + + # Content start for tool result + tool_content_start = { + "event": { + "contentStart": { + "promptName": self.prompt_name, + "contentName": tool_content_name, + "interactive": False, + "type": "TOOL", + "role": "TOOL", + "toolResultInputConfiguration": { + "toolUseId": call_id, + "type": "TEXT", + "textInputConfiguration": { + "mediaType": "text/plain" + } + } + } + } + } + messages.append(json.dumps(tool_content_start)) + + # Tool result + tool_result = { + "event": { + "toolResult": { + "promptName": self.prompt_name, + "contentName": tool_content_name, + "content": output if isinstance(output, str) else json.dumps(output) + } + } + } + messages.append(json.dumps(tool_result)) + + # Content end + tool_content_end = { + "event": { + "contentEnd": { + "promptName": self.prompt_name, + "contentName": tool_content_name, + } + } + } + messages.append(json.dumps(tool_content_end)) + + return messages + + def transform_realtime_response( + self, + message: Union[str, bytes], + model: str, + logging_obj: LiteLLMLoggingObj, + realtime_response_transform_input: RealtimeResponseTransformInput, + ) -> RealtimeResponseTypedDict: + """ + Transform Bedrock Nova Sonic response to OpenAI realtime format. + + Args: + message: Bedrock format message (JSON string) + model: Model ID + logging_obj: Logging object + realtime_response_transform_input: Current state + + Returns: + Transformed response with updated state + """ + try: + json_message = json.loads(message) + except json.JSONDecodeError: + message_preview = message[:200].decode('utf-8', errors='replace') if isinstance(message, bytes) else message[:200] + verbose_logger.warning(f"Invalid JSON message: {message_preview}") + return { + "response": [], + "current_output_item_id": realtime_response_transform_input.get( + "current_output_item_id" + ), + "current_response_id": realtime_response_transform_input.get( + "current_response_id" + ), + "current_delta_chunks": realtime_response_transform_input.get( + "current_delta_chunks" + ), + "current_conversation_id": realtime_response_transform_input.get( + "current_conversation_id" + ), + "current_item_chunks": realtime_response_transform_input.get( + "current_item_chunks" + ), + "current_delta_type": realtime_response_transform_input.get( + "current_delta_type" + ), + "session_configuration_request": realtime_response_transform_input.get( + "session_configuration_request" + ), + } + + # Extract state + current_output_item_id = realtime_response_transform_input.get( + "current_output_item_id" + ) + current_response_id = realtime_response_transform_input.get( + "current_response_id" + ) + current_conversation_id = realtime_response_transform_input.get( + "current_conversation_id" + ) + current_delta_chunks = realtime_response_transform_input.get( + "current_delta_chunks" + ) + current_delta_type = realtime_response_transform_input.get("current_delta_type") + session_configuration_request = realtime_response_transform_input.get( + "session_configuration_request" + ) + + returned_messages: List[OpenAIRealtimeEvents] = [] + + # Parse Bedrock event + event = json_message.get("event", {}) + + # Route to appropriate transformation method + if "sessionStart" in event: + session_created = self.transform_session_start_event( + event, model, logging_obj + ) + returned_messages.append(session_created) + session_configuration_request = json.dumps({"configured": True}) + + elif "contentStart" in event: + ( + events, + current_response_id, + current_output_item_id, + current_conversation_id, + current_delta_type, + ) = self.transform_content_start_event( + event, + current_response_id, + current_output_item_id, + current_conversation_id, + ) + returned_messages.extend(events) + + elif "textOutput" in event: + events, current_delta_chunks = self.transform_text_output_event( + event, + current_output_item_id, + current_response_id, + current_delta_chunks, + ) + returned_messages.extend(events) + + elif "audioOutput" in event: + events = self.transform_audio_output_event( + event, current_output_item_id, current_response_id + ) + returned_messages.extend(events) + + elif "contentEnd" in event: + events, current_delta_chunks = self.transform_content_end_event( + event, + current_output_item_id, + current_response_id, + current_delta_type, + current_delta_chunks, + ) + returned_messages.extend(events) + + elif "toolUse" in event: + events, tool_call_id, tool_name = self.transform_tool_use_event( + event, current_output_item_id, current_response_id + ) + returned_messages.extend(events) + # Store tool call info for potential use + verbose_logger.debug(f"Tool use event: {tool_name} (ID: {tool_call_id})") + + elif "promptEnd" in event: + ( + events, + current_output_item_id, + current_response_id, + current_delta_type, + ) = self.transform_prompt_end_event( + event, current_response_id, current_conversation_id + ) + returned_messages.extend(events) + + return { + "response": returned_messages, + "current_output_item_id": current_output_item_id, + "current_response_id": current_response_id, + "current_delta_chunks": current_delta_chunks, + "current_conversation_id": current_conversation_id, + "current_item_chunks": realtime_response_transform_input.get( + "current_item_chunks" + ), + "current_delta_type": current_delta_type, + "session_configuration_request": session_configuration_request, + } diff --git a/litellm/llms/cerebras/chat.py b/litellm/llms/cerebras/chat.py index 4e9c6811a77..9929e2ab9a2 100644 --- a/litellm/llms/cerebras/chat.py +++ b/litellm/llms/cerebras/chat.py @@ -7,6 +7,7 @@ from typing import Optional from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig +from litellm.utils import supports_reasoning class CerebrasConfig(OpenAIGPTConfig): @@ -24,6 +25,7 @@ class CerebrasConfig(OpenAIGPTConfig): tool_choice: Optional[str] = None tools: Optional[list] = None user: Optional[str] = None + reasoning_effort: Optional[str] = None def __init__( self, @@ -37,6 +39,7 @@ def __init__( tool_choice: Optional[str] = None, tools: Optional[list] = None, user: Optional[str] = None, + reasoning_effort: Optional[str] = None, ) -> None: locals_ = locals().copy() for key, value in locals_.items(): @@ -53,7 +56,7 @@ def get_supported_openai_params(self, model: str) -> list: """ - return [ + supported_params = [ "max_tokens", "max_completion_tokens", "response_format", @@ -67,6 +70,12 @@ def get_supported_openai_params(self, model: str) -> list: "user", ] + # Only add reasoning_effort for models that support it + if supports_reasoning(model=model, custom_llm_provider="cerebras"): + supported_params.append("reasoning_effort") + + return supported_params + def map_openai_params( self, non_default_params: dict, diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py index 4f86877a6c0..ac9dd5998e2 100644 --- a/litellm/llms/custom_httpx/http_handler.py +++ b/litellm/llms/custom_httpx/http_handler.py @@ -50,9 +50,21 @@ except Exception: version = "0.0.0" -headers = { - "User-Agent": f"litellm/{version}", -} +def get_default_headers() -> dict: + """ + Get default headers for HTTP requests. + + - Default: `User-Agent: litellm/{version}` + - Override: set `LITELLM_USER_AGENT` to fully override the header value. + """ + user_agent = os.environ.get("LITELLM_USER_AGENT") + if user_agent is not None: + return {"User-Agent": user_agent} + + return {"User-Agent": f"litellm/{version}"} + +# Initialize headers (User-Agent) +headers = get_default_headers() # https://www.python-httpx.org/advanced/timeouts _DEFAULT_TIMEOUT = httpx.Timeout(timeout=5.0, connect=5.0) @@ -371,13 +383,16 @@ def create_client( shared_session=shared_session, ) + # Get default headers (User-Agent, overridable via LITELLM_USER_AGENT) + default_headers = get_default_headers() + return httpx.AsyncClient( transport=transport, event_hooks=event_hooks, timeout=timeout, verify=ssl_config, cert=cert, - headers=headers, + headers=default_headers, follow_redirects=True, ) @@ -899,6 +914,9 @@ def __init__( # /path/to/client.pem cert = os.getenv("SSL_CERTIFICATE", litellm.ssl_certificate) + # Get default headers (User-Agent, overridable via LITELLM_USER_AGENT) + default_headers = get_default_headers() if not disable_default_headers else None + if client is None: transport = self._create_sync_transport() @@ -908,7 +926,7 @@ def __init__( timeout=timeout, verify=ssl_config, cert=cert, - headers=headers if not disable_default_headers else None, + headers=default_headers, follow_redirects=True, ) else: diff --git a/litellm/llms/custom_httpx/httpx_handler.py b/litellm/llms/custom_httpx/httpx_handler.py index 6f684ba01c2..491cd97f7db 100644 --- a/litellm/llms/custom_httpx/httpx_handler.py +++ b/litellm/llms/custom_httpx/httpx_handler.py @@ -1,3 +1,4 @@ +import os from typing import Optional, Union import httpx @@ -7,13 +8,22 @@ except Exception: version = "0.0.0" -headers = { - "User-Agent": f"litellm/{version}", -} +def get_default_headers() -> dict: + """ + Get default headers for HTTP requests. + - Default: `User-Agent: litellm/{version}` + - Override: set `LITELLM_USER_AGENT` to fully override the header value. + """ + user_agent = os.environ.get("LITELLM_USER_AGENT") + if user_agent is not None: + return {"User-Agent": user_agent} + + return {"User-Agent": f"litellm/{version}"} class HTTPHandler: def __init__(self, concurrent_limit=1000): + headers = get_default_headers() # Create a client with a connection pool self.client = httpx.AsyncClient( limits=httpx.Limits( diff --git a/litellm/llms/databricks/chat/transformation.py b/litellm/llms/databricks/chat/transformation.py index 2b7f5dd5995..e9ae94307d4 100644 --- a/litellm/llms/databricks/chat/transformation.py +++ b/litellm/llms/databricks/chat/transformation.py @@ -298,7 +298,8 @@ def map_openai_params( if "reasoning_effort" in non_default_params and "claude" in model: optional_params["thinking"] = AnthropicConfig._map_reasoning_effort( - non_default_params.get("reasoning_effort") + reasoning_effort=non_default_params.get("reasoning_effort"), + model=model ) optional_params.pop("reasoning_effort", None) ## handle thinking tokens diff --git a/litellm/llms/deprecated_providers/palm.py b/litellm/llms/deprecated_providers/palm.py index 3039222c0e2..657a6fdb229 100644 --- a/litellm/llms/deprecated_providers/palm.py +++ b/litellm/llms/deprecated_providers/palm.py @@ -139,7 +139,7 @@ def completion( ) ## COMPLETION CALL try: - response = palm.generate_text(prompt=prompt, **inference_params) + response = palm.generate_text(prompt=prompt, **inference_params) # type: ignore[attr-defined] except Exception as e: raise PalmError( message=str(e), diff --git a/litellm/llms/fireworks_ai/chat/transformation.py b/litellm/llms/fireworks_ai/chat/transformation.py index 86bcd94450f..7ec32fecc46 100644 --- a/litellm/llms/fireworks_ai/chat/transformation.py +++ b/litellm/llms/fireworks_ai/chat/transformation.py @@ -236,6 +236,10 @@ def _transform_messages_helper( disable_add_transform_inline_image_block=disable_add_transform_inline_image_block, ) filter_value_from_dict(cast(dict, message), "cache_control") + # Remove fields not permitted by FireworksAI that may cause: + # "Not permitted, field: 'messages[n].provider_specific_fields'" + if isinstance(message, dict) and "provider_specific_fields" in message: + cast(dict, message).pop("provider_specific_fields", None) return messages diff --git a/litellm/llms/gemini/files/transformation.py b/litellm/llms/gemini/files/transformation.py index 37f1376c2b1..cc799cfd6aa 100644 --- a/litellm/llms/gemini/files/transformation.py +++ b/litellm/llms/gemini/files/transformation.py @@ -210,7 +210,7 @@ def transform_retrieve_file_request( We expect file_id to be the URI (e.g. https://generativelanguage.googleapis.com/v1beta/files/...) as returned by the upload response. """ - api_key = litellm_params.get("api_key") + api_key = litellm_params.get("api_key") or self.get_api_key() if not api_key: raise ValueError("api_key is required") @@ -222,7 +222,8 @@ def transform_retrieve_file_request( api_base = api_base.rstrip("/") url = "{}/v1beta/{}?key={}".format(api_base, file_id, api_key) - return url, {"Content-Type": "application/json"} + # Return empty params dict - API key is already in URL, no query params needed + return url, {} def transform_retrieve_file_response( self, @@ -299,7 +300,7 @@ def transform_delete_file_request( # Extract the file path from full URI file_name = file_id.split("/v1beta/")[-1] else: - file_name = file_id + file_name = file_id if file_id.startswith("files/") else f"files/{file_id}" # Construct the delete URL url = f"{api_base}/v1beta/{file_name}" diff --git a/litellm/llms/gemini/image_generation/transformation.py b/litellm/llms/gemini/image_generation/transformation.py index 63b835df9d0..73aef15e4c7 100644 --- a/litellm/llms/gemini/image_generation/transformation.py +++ b/litellm/llms/gemini/image_generation/transformation.py @@ -255,9 +255,11 @@ def transform_image_generation_response( if "inlineData" in part: inline_data = part["inlineData"] if "data" in inline_data: + thought_sig = part.get("thoughtSignature") model_response.data.append(ImageObject( b64_json=inline_data["data"], url=None, + provider_specific_fields={"thought_signature": thought_sig} if thought_sig else None, )) # Extract usage metadata for Gemini models diff --git a/litellm/llms/gigachat/chat/transformation.py b/litellm/llms/gigachat/chat/transformation.py index ba14de1f65d..f546f356e11 100644 --- a/litellm/llms/gigachat/chat/transformation.py +++ b/litellm/llms/gigachat/chat/transformation.py @@ -386,33 +386,7 @@ def _transform_messages(self, messages: List[AllMessageValues]) -> List[dict]: transformed.append(message) - # Collapse consecutive user messages - return self._collapse_user_messages(transformed) - - def _collapse_user_messages(self, messages: List[dict]) -> List[dict]: - """Collapse consecutive user messages into one.""" - collapsed: List[dict] = [] - prev_user_msg: Optional[dict] = None - content_parts: List[str] = [] - - for msg in messages: - if msg.get("role") == "user" and prev_user_msg is not None: - content_parts.append(msg.get("content", "")) - else: - if content_parts and prev_user_msg: - prev_user_msg["content"] = "\n".join( - [prev_user_msg.get("content", "")] + content_parts - ) - content_parts = [] - collapsed.append(msg) - prev_user_msg = msg if msg.get("role") == "user" else None - - if content_parts and prev_user_msg: - prev_user_msg["content"] = "\n".join( - [prev_user_msg.get("content", "")] + content_parts - ) - - return collapsed + return transformed def transform_response( self, diff --git a/litellm/llms/github_copilot/chat/transformation.py b/litellm/llms/github_copilot/chat/transformation.py index 50f18cedf9b..be8ad7d0877 100644 --- a/litellm/llms/github_copilot/chat/transformation.py +++ b/litellm/llms/github_copilot/chat/transformation.py @@ -1,11 +1,16 @@ -from typing import Any, Optional, Tuple, cast, List +from typing import List, Optional, Tuple + from litellm.exceptions import AuthenticationError from litellm.llms.openai.openai import OpenAIConfig from litellm.types.llms.openai import AllMessageValues from ..authenticator import Authenticator -from ..common_utils import GetAPIKeyError, GITHUB_COPILOT_API_BASE +from ..common_utils import ( + GITHUB_COPILOT_API_BASE, + GetAPIKeyError, + get_copilot_default_headers, +) class GithubCopilotConfig(OpenAIConfig): @@ -25,9 +30,7 @@ def _get_openai_compatible_provider_info( api_key: Optional[str], custom_llm_provider: str, ) -> Tuple[Optional[str], Optional[str], str]: - dynamic_api_base = ( - self.authenticator.get_api_base() or GITHUB_COPILOT_API_BASE - ) + dynamic_api_base = self.authenticator.get_api_base() or GITHUB_COPILOT_API_BASE try: dynamic_api_key = self.authenticator.get_api_key() except GetAPIKeyError as e: @@ -45,14 +48,24 @@ def _transform_messages( ): import litellm - disable_copilot_system_to_assistant = ( - litellm.disable_copilot_system_to_assistant - ) - if not disable_copilot_system_to_assistant: - for message in messages: - if "role" in message and message["role"] == "system": - cast(Any, message)["role"] = "assistant" - return messages + # Check if system-to-assistant conversion is disabled + if litellm.disable_copilot_system_to_assistant: + # GitHub Copilot API now supports system prompts for all models (Claude, GPT, etc.) + # No conversion needed - just return messages as-is + return messages + + # Default behavior: convert system messages to assistant for compatibility + transformed_messages = [] + for message in messages: + if message.get("role") == "system": + # Convert system message to assistant message + transformed_message = message.copy() + transformed_message["role"] = "assistant" + transformed_messages.append(transformed_message) + else: + transformed_messages.append(message) + + return transformed_messages def validate_environment( self, @@ -69,6 +82,14 @@ def validate_environment( headers, model, messages, optional_params, litellm_params, api_key, api_base ) + # Add Copilot-specific headers (editor-version, user-agent, etc.) + try: + copilot_api_key = self.authenticator.get_api_key() + copilot_headers = get_copilot_default_headers(copilot_api_key) + validated_headers = {**copilot_headers, **validated_headers} + except GetAPIKeyError: + pass # Will be handled later in the request flow + # Add X-Initiator header based on message roles initiator = self._determine_initiator(messages) validated_headers["X-Initiator"] = initiator @@ -87,7 +108,7 @@ def get_supported_openai_params(self, model: str) -> list: For other models, returns standard OpenAI parameters (which may include reasoning_effort for o-series models). """ from litellm.utils import supports_reasoning - + # Get base OpenAI parameters base_params = super().get_supported_openai_params(model) @@ -118,7 +139,7 @@ def _has_vision_content(self, messages: List[AllMessageValues]) -> bool: """ Check if any message contains vision content (images). Returns True if any message has content with vision-related types, otherwise False. - + Checks for: - image_url content type (OpenAI format) - Content items with type 'image_url' diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.py index fb00aa28f45..c406f502b45 100644 --- a/litellm/llms/openai/chat/guardrail_translation/handler.py +++ b/litellm/llms/openai/chat/guardrail_translation/handler.py @@ -21,7 +21,13 @@ from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation from litellm.main import stream_chunk_builder from litellm.types.llms.openai import ChatCompletionToolParam -from litellm.types.utils import Choices, GenericGuardrailAPIInputs, ModelResponse, ModelResponseStream, StreamingChoices +from litellm.types.utils import ( + Choices, + GenericGuardrailAPIInputs, + ModelResponse, + ModelResponseStream, + StreamingChoices, +) if TYPE_CHECKING: from litellm.integrations.custom_guardrail import CustomGuardrail @@ -80,9 +86,9 @@ async def process_input_messages( if tool_calls_to_check: inputs["tool_calls"] = tool_calls_to_check # type: ignore if messages: - inputs["structured_messages"] = ( - messages # pass the openai /chat/completions messages to the guardrail, as-is - ) + inputs[ + "structured_messages" + ] = messages # pass the openai /chat/completions messages to the guardrail, as-is # Pass tools (function definitions) to the guardrail tools = data.get("tools") if tools: @@ -362,14 +368,17 @@ async def process_output_streaming_response( # check if the stream has ended has_stream_ended = False for chunk in responses_so_far: - if chunk.choices[0].finish_reason is not None: + if chunk.choices and chunk.choices[0].finish_reason is not None: has_stream_ended = True break if has_stream_ended: # convert to model response model_response = cast( - ModelResponse, stream_chunk_builder(chunks=responses_so_far, logging_obj=litellm_logging_obj) + ModelResponse, + stream_chunk_builder( + chunks=responses_so_far, logging_obj=litellm_logging_obj + ), ) # run process_output_response await self.process_output_response( diff --git a/litellm/llms/openai/common_utils.py b/litellm/llms/openai/common_utils.py index 8bcecd35232..ce470f04aca 100644 --- a/litellm/llms/openai/common_utils.py +++ b/litellm/llms/openai/common_utils.py @@ -15,14 +15,12 @@ from aiohttp import ClientSession import litellm -from litellm._logging import verbose_logger from litellm.llms.base_llm.chat.transformation import BaseLLMException from litellm.llms.custom_httpx.http_handler import ( _DEFAULT_TTL_FOR_HTTPX_CLIENTS, AsyncHTTPHandler, get_ssl_configuration, ) -from litellm.types.utils import LlmProviders class OpenAIError(BaseLLMException): @@ -205,67 +203,30 @@ def _get_async_http_client( if litellm.aclient_session is not None: return litellm.aclient_session - # Use the global cached client system to prevent memory leaks (issue #14540) - # This routes through get_async_httpx_client() which provides TTL-based caching - from litellm.llms.custom_httpx.http_handler import get_async_httpx_client + # Get unified SSL configuration + ssl_config = get_ssl_configuration() - try: - # Get SSL config and include in params for proper cache key - ssl_config = get_ssl_configuration() - params = {"ssl_verify": ssl_config} if ssl_config is not None else {} - params["disable_aiohttp_transport"] = litellm.disable_aiohttp_transport - - # Get a cached AsyncHTTPHandler which manages the httpx.AsyncClient - cached_handler = get_async_httpx_client( - llm_provider=LlmProviders.OPENAI, # Cache key includes provider - params=params, # Include SSL config in cache key + return httpx.AsyncClient( + verify=ssl_config, + transport=AsyncHTTPHandler._create_async_transport( + ssl_context=ssl_config + if isinstance(ssl_config, ssl.SSLContext) + else None, + ssl_verify=ssl_config if isinstance(ssl_config, bool) else None, shared_session=shared_session, - ) - # Return the underlying httpx client from the handler - return cached_handler.client - except (ImportError, AttributeError, KeyError) as e: - # Fallback to creating a client directly if caching system unavailable - # This preserves backwards compatibility - verbose_logger.debug( - f"Client caching unavailable ({type(e).__name__}), using direct client creation" - ) - ssl_config = get_ssl_configuration() - return httpx.AsyncClient( - verify=ssl_config, - transport=AsyncHTTPHandler._create_async_transport( - ssl_context=ssl_config - if isinstance(ssl_config, ssl.SSLContext) - else None, - ssl_verify=ssl_config if isinstance(ssl_config, bool) else None, - shared_session=shared_session, - ), - follow_redirects=True, - ) + ), + follow_redirects=True, + ) @staticmethod def _get_sync_http_client() -> Optional[httpx.Client]: if litellm.client_session is not None: return litellm.client_session - # Use the global cached client system to prevent memory leaks (issue #14540) - from litellm.llms.custom_httpx.http_handler import _get_httpx_client - - try: - # Get SSL config and include in params for proper cache key - ssl_config = get_ssl_configuration() - params = {"ssl_verify": ssl_config} if ssl_config is not None else None - - # Get a cached HTTPHandler which manages the httpx.Client - cached_handler = _get_httpx_client(params=params) - # Return the underlying httpx client from the handler - return cached_handler.client - except (ImportError, AttributeError, KeyError) as e: - # Fallback to creating a client directly if caching system unavailable - verbose_logger.debug( - f"Client caching unavailable ({type(e).__name__}), using direct client creation" - ) - ssl_config = get_ssl_configuration() - return httpx.Client( - verify=ssl_config, - follow_redirects=True, - ) + # Get unified SSL configuration + ssl_config = get_ssl_configuration() + + return httpx.Client( + verify=ssl_config, + follow_redirects=True, + ) diff --git a/litellm/llms/openai/embeddings/guardrail_translation/__init__.py b/litellm/llms/openai/embeddings/guardrail_translation/__init__.py new file mode 100644 index 00000000000..a60662282ca --- /dev/null +++ b/litellm/llms/openai/embeddings/guardrail_translation/__init__.py @@ -0,0 +1,13 @@ +"""OpenAI Embeddings handler for Unified Guardrails.""" + +from litellm.llms.openai.embeddings.guardrail_translation.handler import ( + OpenAIEmbeddingsHandler, +) +from litellm.types.utils import CallTypes + +guardrail_translation_mappings = { + CallTypes.embedding: OpenAIEmbeddingsHandler, + CallTypes.aembedding: OpenAIEmbeddingsHandler, +} + +__all__ = ["guardrail_translation_mappings", "OpenAIEmbeddingsHandler"] diff --git a/litellm/llms/openai/embeddings/guardrail_translation/handler.py b/litellm/llms/openai/embeddings/guardrail_translation/handler.py new file mode 100644 index 00000000000..7458020e109 --- /dev/null +++ b/litellm/llms/openai/embeddings/guardrail_translation/handler.py @@ -0,0 +1,179 @@ +""" +OpenAI Embeddings Handler for Unified Guardrails + +This module provides guardrail translation support for OpenAI's embeddings endpoint. +The handler processes the 'input' parameter for guardrails. +""" + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from litellm._logging import verbose_proxy_logger +from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation +from litellm.types.utils import GenericGuardrailAPIInputs + +if TYPE_CHECKING: + from litellm.integrations.custom_guardrail import CustomGuardrail + from litellm.types.utils import EmbeddingResponse + + +class OpenAIEmbeddingsHandler(BaseTranslation): + """ + Handler for processing OpenAI embeddings requests with guardrails. + + This class provides methods to: + 1. Process input text (pre-call hook) + 2. Process output response (post-call hook) - embeddings don't typically need output guardrails + + The handler specifically processes the 'input' parameter which can be: + - A single string + - A list of strings (for batch embeddings) + - A list of integers (token IDs - not processed by guardrails) + - A list of lists of integers (batch token IDs - not processed by guardrails) + """ + + async def process_input_messages( + self, + data: dict, + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional[Any] = None, + ) -> Any: + """ + Process input text by applying guardrails to text content. + + Args: + data: Request data dictionary containing 'input' parameter + guardrail_to_apply: The guardrail instance to apply + litellm_logging_obj: Optional logging object + + Returns: + Modified data with guardrails applied to input + """ + input_data = data.get("input") + if input_data is None: + verbose_proxy_logger.debug( + "OpenAI Embeddings: No input found in request data" + ) + return data + + if isinstance(input_data, str): + data = await self._process_string_input( + data, input_data, guardrail_to_apply, litellm_logging_obj + ) + elif isinstance(input_data, list): + data = await self._process_list_input( + data, input_data, guardrail_to_apply, litellm_logging_obj + ) + else: + verbose_proxy_logger.warning( + "OpenAI Embeddings: Unexpected input type: %s. Expected string or list.", + type(input_data), + ) + + return data + + async def _process_string_input( + self, + data: dict, + input_data: str, + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional[Any], + ) -> dict: + """Process a single string input through the guardrail.""" + inputs = GenericGuardrailAPIInputs(texts=[input_data]) + if model := data.get("model"): + inputs["model"] = model + + guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + inputs=inputs, + request_data=data, + input_type="request", + logging_obj=litellm_logging_obj, + ) + + if guardrailed_texts := guardrailed_inputs.get("texts"): + data["input"] = guardrailed_texts[0] + verbose_proxy_logger.debug( + "OpenAI Embeddings: Applied guardrail to string input. " + "Original length: %d, New length: %d", + len(input_data), + len(data["input"]), + ) + + return data + + async def _process_list_input( + self, + data: dict, + input_data: List[Union[str, int, List[int]]], + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional[Any], + ) -> dict: + """Process a list input through the guardrail (if it contains strings).""" + if len(input_data) == 0: + return data + + first_item = input_data[0] + + # Skip non-text inputs (token IDs) + if isinstance(first_item, (int, list)): + verbose_proxy_logger.debug( + "OpenAI Embeddings: Input is token IDs, skipping guardrail processing" + ) + return data + + if not isinstance(first_item, str): + verbose_proxy_logger.warning( + "OpenAI Embeddings: Unexpected input list item type: %s", + type(first_item), + ) + return data + + # List of strings - apply guardrail + inputs = GenericGuardrailAPIInputs(texts=input_data) # type: ignore + if model := data.get("model"): + inputs["model"] = model + + guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + inputs=inputs, + request_data=data, + input_type="request", + logging_obj=litellm_logging_obj, + ) + + if guardrailed_texts := guardrailed_inputs.get("texts"): + data["input"] = guardrailed_texts + verbose_proxy_logger.debug( + "OpenAI Embeddings: Applied guardrail to %d inputs", + len(guardrailed_texts), + ) + + return data + + async def process_output_response( + self, + response: "EmbeddingResponse", + guardrail_to_apply: "CustomGuardrail", + litellm_logging_obj: Optional[Any] = None, + user_api_key_dict: Optional[Any] = None, + ) -> Any: + """ + Process output response - embeddings responses contain vectors, not text. + + For embeddings, the output is numerical vectors, so there's typically + no text content to apply guardrails to. This method is a no-op but + is included for interface consistency. + + Args: + response: Embedding response object + guardrail_to_apply: The guardrail instance to apply + litellm_logging_obj: Optional logging object + user_api_key_dict: User API key metadata + + Returns: + Unmodified response (embeddings don't have text output to guard) + """ + verbose_proxy_logger.debug( + "OpenAI Embeddings: Output response processing skipped - " + "embeddings contain vectors, not text" + ) + return response diff --git a/litellm/llms/openai/realtime/handler.py b/litellm/llms/openai/realtime/handler.py index fd04ac4d458..ef9cc43c3e1 100644 --- a/litellm/llms/openai/realtime/handler.py +++ b/litellm/llms/openai/realtime/handler.py @@ -16,6 +16,62 @@ class OpenAIRealtime(OpenAIChatCompletion): + """ + Base handler for OpenAI-compatible realtime WebSocket connections. + + Subclasses can override template methods to customize: + - _get_default_api_base(): Default API base URL + - _get_additional_headers(): Extra headers beyond Authorization + - _get_ssl_config(): SSL configuration for WebSocket connection + """ + + def _get_default_api_base(self) -> str: + """ + Get the default API base URL for this provider. + Override this in subclasses to set provider-specific defaults. + """ + return "https://api.openai.com/" + + def _get_additional_headers(self, api_key: str) -> dict: + """ + Get additional headers beyond Authorization. + Override this in subclasses to customize headers (e.g., remove OpenAI-Beta). + + Args: + api_key: API key for authentication + + Returns: + Dictionary of additional headers + """ + return { + "Authorization": f"Bearer {api_key}", + "OpenAI-Beta": "realtime=v1", + } + + def _get_ssl_config(self, url: str) -> Any: + """ + Get SSL configuration for WebSocket connection. + Override this in subclasses to customize SSL behavior. + + Args: + url: WebSocket URL (ws:// or wss://) + + Returns: + SSL configuration (None, True, or SSLContext) + """ + if url.startswith("ws://"): + return None + + # Use the shared SSL context which respects custom CA certs and SSL settings + ssl_config = get_shared_realtime_ssl_context() + + # If ssl_config is False (ssl_verify=False), websockets library needs True instead + # to establish connection without verification (False would fail) + if ssl_config is False: + return True + + return ssl_config + def _construct_url(self, api_base: str, query_params: RealtimeQueryParams) -> str: """ Construct the backend websocket URL with all query parameters (including 'model'). @@ -45,8 +101,9 @@ async def async_realtime( ): import websockets from websockets.asyncio.client import ClientConnection + if api_base is None: - api_base = "https://api.openai.com/" + api_base = self._get_default_api_base() if api_key is None: raise ValueError("api_key is required for OpenAI realtime calls") @@ -56,30 +113,27 @@ async def async_realtime( url = self._construct_url(api_base, query_params) try: - # Only use SSL context for secure websocket connections (wss://) - # websockets library doesn't accept ssl argument for ws:// URIs - ssl_context = None if url.startswith("ws://") else get_shared_realtime_ssl_context() + # Get provider-specific SSL configuration + ssl_config = self._get_ssl_config(url) + + # Get provider-specific headers + headers = self._get_additional_headers(api_key) + # Log a masked request preview consistent with other endpoints. logging_obj.pre_call( input=None, api_key=api_key, additional_args={ "api_base": url, - "headers": { - "Authorization": f"Bearer {api_key}", - "OpenAI-Beta": "realtime=v1", - }, + "headers": headers, "complete_input_dict": {"query_params": query_params}, }, ) async with websockets.connect( # type: ignore url, - additional_headers={ - "Authorization": f"Bearer {api_key}", # type: ignore - "OpenAI-Beta": "realtime=v1", - }, + additional_headers=headers, # type: ignore max_size=REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, - ssl=ssl_context, + ssl=ssl_config, ) as backend_ws: realtime_streaming = RealTimeStreaming( websocket, cast(ClientConnection, backend_ws), logging_obj diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py index d943662f9e4..ad3d4c932d4 100644 --- a/litellm/llms/openai/responses/guardrail_translation/handler.py +++ b/litellm/llms/openai/responses/guardrail_translation/handler.py @@ -319,9 +319,7 @@ async def process_output_response( return response if not response_output: - verbose_proxy_logger.debug( - "OpenAI Responses API: Empty output in response" - ) + verbose_proxy_logger.debug("OpenAI Responses API: Empty output in response") return response # Step 1: Extract all text content and tool calls from response output @@ -427,27 +425,30 @@ async def process_output_streaming_response( handle_raw_dict_callback=None, ) - tool_calls = model_response_choices[0].message.tool_calls - text = model_response_choices[0].message.content - guardrail_inputs = GenericGuardrailAPIInputs() - if text: - guardrail_inputs["texts"] = [text] - if tool_calls: - guardrail_inputs["tool_calls"] = cast( - List[ChatCompletionToolCallChunk], tool_calls - ) - # Include model information from the response if available - response_model = final_chunk.get("response", {}).get("model") - if response_model: - guardrail_inputs["model"] = response_model - if tool_calls or text: - _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( - inputs=guardrail_inputs, - request_data={}, - input_type="response", - logging_obj=litellm_logging_obj, - ) - return responses_so_far + if model_response_choices: + tool_calls = model_response_choices[0].message.tool_calls + text = model_response_choices[0].message.content + guardrail_inputs = GenericGuardrailAPIInputs() + if text: + guardrail_inputs["texts"] = [text] + if tool_calls: + guardrail_inputs["tool_calls"] = cast( + List[ChatCompletionToolCallChunk], tool_calls + ) + # Include model information from the response if available + response_model = final_chunk.get("response", {}).get("model") + if response_model: + guardrail_inputs["model"] = response_model + if tool_calls or text: + _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + inputs=guardrail_inputs, + request_data={}, + input_type="response", + logging_obj=litellm_logging_obj, + ) + return responses_so_far + else: + verbose_proxy_logger.debug("Skipping output guardrail - model response has no choices") # model_response_stream = OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(final_chunk) # tool_calls = model_response_stream.choices[0].tool_calls # convert openai response to model response @@ -513,11 +514,9 @@ def _has_text_content(self, response: "ResponsesAPIResponse") -> bool: # Check if it's an OutputText with text if isinstance(content_item, OutputText): if content_item.text: - return True elif isinstance(content_item, dict): if content_item.get("text"): - return True return False diff --git a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py index 289963e917a..ed4d2d6a740 100644 --- a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py +++ b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py @@ -27,6 +27,8 @@ type=LiteLLMCacheType.LOCAL ) # only used for calling 'get_cache_key' function +MAX_PAGINATION_PAGES = 100 # Reasonable upper bound for pagination + class ContextCachingEndpoints(VertexBase): """ @@ -115,7 +117,7 @@ def check_cache( - None """ - _, url = self._get_token_and_url_context_caching( + _, base_url = self._get_token_and_url_context_caching( gemini_api_key=api_key, custom_llm_provider=custom_llm_provider, api_base=api_base, @@ -123,43 +125,63 @@ def check_cache( vertex_location=vertex_location, vertex_auth_header=vertex_auth_header ) - try: - ## LOGGING - logging_obj.pre_call( - input="", - api_key="", - additional_args={ - "complete_input_dict": {}, - "api_base": url, - "headers": headers, - }, - ) - resp = client.get(url=url, headers=headers) - resp.raise_for_status() - except httpx.HTTPStatusError as e: - if e.response.status_code == 403: + page_token: Optional[str] = None + + # Iterate through all pages + for _ in range(MAX_PAGINATION_PAGES): + # Build URL with pagination token if present + if page_token: + separator = "&" if "?" in base_url else "?" + url = f"{base_url}{separator}pageToken={page_token}" + else: + url = base_url + + try: + ## LOGGING + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "complete_input_dict": {}, + "api_base": url, + "headers": headers, + }, + ) + + resp = client.get(url=url, headers=headers) + resp.raise_for_status() + except httpx.HTTPStatusError as e: + if e.response.status_code == 403: + return None + raise VertexAIError( + status_code=e.response.status_code, message=e.response.text + ) + except Exception as e: + raise VertexAIError(status_code=500, message=str(e)) + + raw_response = resp.json() + logging_obj.post_call(original_response=raw_response) + + if "cachedContents" not in raw_response: return None - raise VertexAIError( - status_code=e.response.status_code, message=e.response.text - ) - except Exception as e: - raise VertexAIError(status_code=500, message=str(e)) - raw_response = resp.json() - logging_obj.post_call(original_response=raw_response) - if "cachedContents" not in raw_response: - return None + all_cached_items = CachedContentListAllResponseBody(**raw_response) - all_cached_items = CachedContentListAllResponseBody(**raw_response) + if "cachedContents" not in all_cached_items: + return None - if "cachedContents" not in all_cached_items: - return None + # Check current page for matching cache_key + for cached_item in all_cached_items["cachedContents"]: + display_name = cached_item.get("displayName") + if display_name is not None and display_name == cache_key: + return cached_item.get("name") - for cached_item in all_cached_items["cachedContents"]: - display_name = cached_item.get("displayName") - if display_name is not None and display_name == cache_key: - return cached_item.get("name") + # Check if there are more pages + page_token = all_cached_items.get("nextPageToken") + if not page_token: + # No more pages, cache not found + break return None @@ -187,7 +209,7 @@ async def async_check_cache( - None """ - _, url = self._get_token_and_url_context_caching( + _, base_url = self._get_token_and_url_context_caching( gemini_api_key=api_key, custom_llm_provider=custom_llm_provider, api_base=api_base, @@ -195,43 +217,63 @@ async def async_check_cache( vertex_location=vertex_location, vertex_auth_header=vertex_auth_header ) - try: - ## LOGGING - logging_obj.pre_call( - input="", - api_key="", - additional_args={ - "complete_input_dict": {}, - "api_base": url, - "headers": headers, - }, - ) - resp = await client.get(url=url, headers=headers) - resp.raise_for_status() - except httpx.HTTPStatusError as e: - if e.response.status_code == 403: + page_token: Optional[str] = None + + # Iterate through all pages + for _ in range(MAX_PAGINATION_PAGES): + # Build URL with pagination token if present + if page_token: + separator = "&" if "?" in base_url else "?" + url = f"{base_url}{separator}pageToken={page_token}" + else: + url = base_url + + try: + ## LOGGING + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "complete_input_dict": {}, + "api_base": url, + "headers": headers, + }, + ) + + resp = await client.get(url=url, headers=headers) + resp.raise_for_status() + except httpx.HTTPStatusError as e: + if e.response.status_code == 403: + return None + raise VertexAIError( + status_code=e.response.status_code, message=e.response.text + ) + except Exception as e: + raise VertexAIError(status_code=500, message=str(e)) + + raw_response = resp.json() + logging_obj.post_call(original_response=raw_response) + + if "cachedContents" not in raw_response: return None - raise VertexAIError( - status_code=e.response.status_code, message=e.response.text - ) - except Exception as e: - raise VertexAIError(status_code=500, message=str(e)) - raw_response = resp.json() - logging_obj.post_call(original_response=raw_response) - if "cachedContents" not in raw_response: - return None + all_cached_items = CachedContentListAllResponseBody(**raw_response) - all_cached_items = CachedContentListAllResponseBody(**raw_response) + if "cachedContents" not in all_cached_items: + return None - if "cachedContents" not in all_cached_items: - return None + # Check current page for matching cache_key + for cached_item in all_cached_items["cachedContents"]: + display_name = cached_item.get("displayName") + if display_name is not None and display_name == cache_key: + return cached_item.get("name") - for cached_item in all_cached_items["cachedContents"]: - display_name = cached_item.get("displayName") - if display_name is not None and display_name == cache_key: - return cached_item.get("name") + # Check if there are more pages + page_token = all_cached_items.get("nextPageToken") + if not page_token: + # No more pages, cache not found + break return None @@ -501,4 +543,4 @@ def get_cache(self): pass async def async_get_cache(self): - pass + pass \ No newline at end of file diff --git a/litellm/llms/vertex_ai/files/transformation.py b/litellm/llms/vertex_ai/files/transformation.py index b3612113ec2..2470c59bbac 100644 --- a/litellm/llms/vertex_ai/files/transformation.py +++ b/litellm/llms/vertex_ai/files/transformation.py @@ -165,7 +165,7 @@ def get_complete_file_url( """ Get the complete url for the request """ - bucket_name = litellm_params.get("bucket_name") or os.getenv("GCS_BUCKET_NAME") + bucket_name = litellm_params.get("bucket_name") or litellm_params.get("litellm_metadata", {}).pop("gcs_bucket_name", None) or os.getenv("GCS_BUCKET_NAME") if not bucket_name: raise ValueError("GCS bucket_name is required") file_data = data.get("file") diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py index a9ac21bb56f..04ae4b6beb8 100644 --- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py +++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py @@ -478,6 +478,13 @@ def _map_function( # noqa: PLR0915 if "type" in tool and tool["type"] == "computer_use": computer_use_config = {k: v for k, v in tool.items() if k != "type"} tool = {VertexToolName.COMPUTER_USE.value: computer_use_config} + # Handle OpenAI-style web_search and web_search_preview tools + # Transform them to Gemini's googleSearch tool + elif "type" in tool and tool["type"] in ("web_search", "web_search_preview"): + verbose_logger.info( + f"Gemini: Transforming OpenAI-style '{tool['type']}' tool to googleSearch" + ) + tool = {VertexToolName.GOOGLE_SEARCH.value: {}} # Handle tools with 'type' field (OpenAI spec compliance) Ignore this field -> https://github.com/BerriAI/litellm/issues/14644#issuecomment-3342061838 elif "type" in tool: tool = {k: tool[k] for k in tool if k != "type"} @@ -1725,6 +1732,52 @@ def _check_finish_reason( else: return "stop" + @staticmethod + def _check_prompt_level_content_filter( + processed_chunk: GenerateContentResponseBody, + response_id: Optional[str], + ) -> Optional["ModelResponseStream"]: + """ + Check if prompt is blocked due to content filtering at the prompt level. + + This handles the case where Vertex AI blocks the prompt before generation begins, + indicated by promptFeedback.blockReason being present. + + Args: + processed_chunk: The parsed response chunk from Vertex AI + response_id: The response ID from the chunk + + Returns: + ModelResponseStream with content_filter finish_reason if blocked, None otherwise. + + Note: + This is consistent with non-streaming _handle_blocked_response() behavior. + Candidate-level content filtering (SAFETY, RECITATION, etc.) is handled + separately via _process_candidates() → _check_finish_reason(). + """ + from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices + + # Check if prompt is blocked due to content filtering + prompt_feedback = processed_chunk.get("promptFeedback") + if prompt_feedback and "blockReason" in prompt_feedback: + verbose_logger.debug( + f"Prompt blocked due to: {prompt_feedback.get('blockReason')} - {prompt_feedback.get('blockReasonMessage')}" + ) + + # Create a content_filter response (consistent with non-streaming _handle_blocked_response) + choice = StreamingChoices( + finish_reason="content_filter", + index=0, + delta=Delta(content=None, role="assistant"), + logprobs=None, + enhancements=None, + ) + + model_response = ModelResponseStream(choices=[choice], id=response_id) + return model_response + + return None + @staticmethod def _calculate_web_search_requests(grounding_metadata: List[dict]) -> Optional[int]: web_search_requests: Optional[int] = None @@ -2806,6 +2859,15 @@ def chunk_parser(self, chunk: dict) -> Optional["ModelResponseStream"]: processed_chunk = GenerateContentResponseBody(**chunk) # type: ignore response_id = processed_chunk.get("responseId") model_response = ModelResponseStream(choices=[], id=response_id) + + # Check if prompt is blocked due to content filtering + blocked_response = VertexGeminiConfig._check_prompt_level_content_filter( + processed_chunk=processed_chunk, + response_id=response_id, + ) + if blocked_response is not None: + model_response = blocked_response + usage: Optional[Usage] = None _candidates: Optional[List[Candidates]] = processed_chunk.get("candidates") grounding_metadata: List[dict] = [] diff --git a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py index 89ed9f1a8a5..ba3df88be14 100644 --- a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py +++ b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py @@ -295,9 +295,11 @@ def transform_image_generation_response( if "inlineData" in part: inline_data = part["inlineData"] if "data" in inline_data: + thought_sig = part.get("thoughtSignature") model_response.data.append(ImageObject( b64_json=inline_data["data"], url=None, + provider_specific_fields={"thought_signature": thought_sig} if thought_sig else None, )) if usage_metadata := response_data.get("usageMetadata", None): diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py index 9b8ff3ecc2d..918b8ecc225 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py @@ -1,5 +1,8 @@ from typing import Any, Dict, List, Optional, Tuple +from litellm.anthropic_beta_headers_manager import ( + update_headers_with_filtered_beta, +) from litellm.llms.anthropic.common_utils import AnthropicModelInfo from litellm.llms.anthropic.experimental_pass_through.messages.transformation import ( AnthropicMessagesConfig, @@ -7,7 +10,6 @@ from litellm.types.llms.anthropic import ( ANTHROPIC_BETA_HEADER_VALUES, ANTHROPIC_HOSTED_TOOLS, - ANTHROPIC_PROMPT_CACHING_SCOPE_BETA_HEADER, ) from litellm.types.llms.anthropic_tool_search import get_tool_search_beta_header from litellm.types.llms.vertex_ai import VertexPartnerProvider @@ -65,10 +67,6 @@ def validate_anthropic_messages_environment( existing_beta = headers.get("anthropic-beta") if existing_beta: beta_values.update(b.strip() for b in existing_beta.split(",")) - - # Use the helper to remove unsupported beta headers - self.remove_unsupported_beta(headers) - beta_values.discard(ANTHROPIC_PROMPT_CACHING_SCOPE_BETA_HEADER) # Check for web search tool for tool in tools: @@ -84,6 +82,12 @@ def validate_anthropic_messages_environment( if beta_values: headers["anthropic-beta"] = ",".join(beta_values) + # Filter out unsupported beta headers for Vertex AI + headers = update_headers_with_filtered_beta( + headers=headers, + provider="vertex_ai", + ) + return headers, api_base def get_complete_url( @@ -128,23 +132,3 @@ def transform_anthropic_messages_request( ) # do not pass output_format in request body to vertex ai - vertex ai does not support output_format as yet return anthropic_messages_request - - def remove_unsupported_beta(self, headers: dict) -> None: - """ - Helper method to remove unsupported beta headers from the beta headers. - Modifies headers in place. - """ - unsupported_beta_headers = [ - ANTHROPIC_PROMPT_CACHING_SCOPE_BETA_HEADER - ] - existing_beta = headers.get("anthropic-beta") - if existing_beta: - filtered_beta = [ - b.strip() - for b in existing_beta.split(",") - if b.strip() not in unsupported_beta_headers - ] - if filtered_beta: - headers["anthropic-beta"] = ",".join(filtered_beta) - elif "anthropic-beta" in headers: - del headers["anthropic-beta"] diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py index 1df07f405e6..0b728d88e76 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py @@ -51,6 +51,40 @@ class VertexAIAnthropicConfig(AnthropicConfig): def custom_llm_provider(self) -> Optional[str]: return "vertex_ai" + def _add_context_management_beta_headers( + self, beta_set: set, context_management: dict + ) -> None: + """ + Add context_management beta headers to the beta_set. + + - If any edit has type "compact_20260112", add compact-2026-01-12 header + - For all other edits, add context-management-2025-06-27 header + + Args: + beta_set: Set of beta headers to modify in-place + context_management: The context_management dict from optional_params + """ + from litellm.types.llms.anthropic import ANTHROPIC_BETA_HEADER_VALUES + + edits = context_management.get("edits", []) + has_compact = False + has_other = False + + for edit in edits: + edit_type = edit.get("type", "") + if edit_type == "compact_20260112": + has_compact = True + else: + has_other = True + + # Add compact header if any compact edits exist + if has_compact: + beta_set.add(ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value) + + # Add context management header if any other edits exist + if has_other: + beta_set.add(ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value) + def transform_request( self, model: str, @@ -86,6 +120,11 @@ def transform_request( beta_set = set(auto_betas) if tool_search_used: beta_set.add("tool-search-tool-2025-10-19") # Vertex requires this header for tool search + + # Add context_management beta headers (compact and/or context-management) + context_management = optional_params.get("context_management") + if context_management: + self._add_context_management_beta_headers(beta_set, context_management) if beta_set: data["anthropic_beta"] = list(beta_set) diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.py index a185370e376..4613b6a5715 100644 --- a/litellm/llms/vertex_ai/vertex_llm_base.py +++ b/litellm/llms/vertex_ai/vertex_llm_base.py @@ -20,6 +20,7 @@ _get_vertex_url, all_gemini_url_modes, get_vertex_base_model_name, + get_vertex_base_url, is_global_only_vertex_model, ) @@ -200,12 +201,7 @@ def get_api_base( ) -> str: if api_base: return api_base - elif vertex_location == "global": - return "https://aiplatform.googleapis.com" - elif vertex_location: - return f"https://{vertex_location}-aiplatform.googleapis.com" - else: - return f"https://{self.get_default_vertex_location()}-aiplatform.googleapis.com" + return get_vertex_base_url(vertex_location or self.get_default_vertex_location()) @staticmethod def create_vertex_url( @@ -218,7 +214,8 @@ def create_vertex_url( ) -> str: """Return the base url for the vertex partner models""" - api_base = api_base or f"https://{vertex_location}-aiplatform.googleapis.com" + if api_base is None: + api_base = get_vertex_base_url(vertex_location) if partner == VertexPartnerProvider.llama: return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/endpoints/openapi/chat/completions" elif partner == VertexPartnerProvider.mistralai: @@ -247,11 +244,13 @@ def get_complete_vertex_url( stream: Optional[bool], model: str, ) -> str: + # Use get_vertex_region to handle global-only models + resolved_location = self.get_vertex_region(vertex_location, model) api_base = self.get_api_base( - api_base=custom_api_base, vertex_location=vertex_location + api_base=custom_api_base, vertex_location=resolved_location ) default_api_base = VertexBase.create_vertex_url( - vertex_location=vertex_location or "us-central1", + vertex_location=resolved_location, vertex_project=vertex_project or project_id, partner=partner, stream=stream, @@ -274,7 +273,7 @@ def get_complete_vertex_url( url=default_api_base, model=model, vertex_project=vertex_project or project_id, - vertex_location=vertex_location or "us-central1", + vertex_location=resolved_location, vertex_api_version="v1", # Partner models typically use v1 ) return api_base diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.py index 245e10e45c1..21782fc6fbf 100644 --- a/litellm/llms/xai/chat/transformation.py +++ b/litellm/llms/xai/chat/transformation.py @@ -4,6 +4,7 @@ import litellm from litellm._logging import verbose_logger +from litellm.constants import XAI_API_BASE from litellm.litellm_core_utils.prompt_templates.common_utils import ( filter_value_from_dict, strip_name_from_messages, @@ -14,8 +15,6 @@ from ...openai.chat.gpt_transformation import OpenAIGPTConfig -XAI_API_BASE = "https://api.x.ai/v1" - class XAIChatConfig(OpenAIGPTConfig): @property diff --git a/litellm/llms/xai/realtime/__init__.py b/litellm/llms/xai/realtime/__init__.py new file mode 100644 index 00000000000..3b0d345f2c2 --- /dev/null +++ b/litellm/llms/xai/realtime/__init__.py @@ -0,0 +1,5 @@ +"""xAI Realtime API handler.""" + +from .handler import XAIRealtime + +__all__ = ["XAIRealtime"] diff --git a/litellm/llms/xai/realtime/handler.py b/litellm/llms/xai/realtime/handler.py new file mode 100644 index 00000000000..c79477ba1df --- /dev/null +++ b/litellm/llms/xai/realtime/handler.py @@ -0,0 +1,38 @@ +""" +This file contains the handler for xAI's Grok Voice Agent API `/v1/realtime` endpoint. + +xAI's Realtime API is fully OpenAI-compatible, so we inherit from OpenAIRealtime +and only override the configuration differences. + +This requires websockets, and is currently only supported on LiteLLM Proxy. +""" + +from litellm.constants import XAI_API_BASE + +from ...openai.realtime.handler import OpenAIRealtime + + +class XAIRealtime(OpenAIRealtime): + """ + Handler for xAI Grok Voice Agent API. + + xAI's Realtime API uses the same WebSocket protocol as OpenAI but with: + - Different endpoint: wss://api.x.ai/v1/realtime (via _get_default_api_base) + - No OpenAI-Beta header required (via _get_additional_headers) + - Model: grok-4-1-fast-non-reasoning + + All WebSocket logic is inherited from OpenAIRealtime. + """ + + def _get_default_api_base(self) -> str: + """xAI uses a different API base URL.""" + return XAI_API_BASE + + def _get_additional_headers(self, api_key: str) -> dict: + """ + xAI does NOT require the OpenAI-Beta header. + Only send Authorization header. + """ + return { + "Authorization": f"Bearer {api_key}", + } diff --git a/litellm/llms/xai/responses/transformation.py b/litellm/llms/xai/responses/transformation.py index 82b4771fb4d..95873aab846 100644 --- a/litellm/llms/xai/responses/transformation.py +++ b/litellm/llms/xai/responses/transformation.py @@ -2,6 +2,7 @@ import litellm from litellm._logging import verbose_logger +from litellm.constants import XAI_API_BASE from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig from litellm.secret_managers.main import get_secret_str from litellm.types.llms.openai import ResponsesAPIOptionalRequestParams @@ -16,8 +17,6 @@ else: LiteLLMLoggingObj = Any -XAI_API_BASE = "https://api.x.ai/v1" - class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): """ diff --git a/litellm/main.py b/litellm/main.py index 13361c644cb..bca023e65ec 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -1199,6 +1199,13 @@ def completion( # type: ignore # noqa: PLR0915 headers = {} if extra_headers is not None: headers.update(extra_headers) + # Inject proxy auth headers if configured + if litellm.proxy_auth is not None: + try: + proxy_headers = litellm.proxy_auth.get_auth_headers() + headers.update(proxy_headers) + except Exception as e: + verbose_logger.warning(f"Failed to get proxy auth headers: {e}") num_retries = kwargs.get( "num_retries", None ) ## alt. param for 'max_retries'. Use this to pass retries w/ instructor. @@ -2199,6 +2206,48 @@ def completion( # type: ignore # noqa: PLR0915 logging_obj=logging, # model call logging done inside the class as we make need to modify I/O to fit aleph alpha's requirements client=client, ) + elif custom_llm_provider == "a2a": + # A2A (Agent-to-Agent) Protocol + # Resolve agent configuration from registry if model format is "a2a/" + api_base, api_key, headers = litellm.A2AConfig.resolve_agent_config_from_registry( + model=model, + api_base=api_base, + api_key=api_key, + headers=headers, + optional_params=optional_params, + ) + + # Fall back to environment variables and defaults + api_base = api_base or litellm.api_base or get_secret_str("A2A_API_BASE") + + if api_base is None: + raise Exception( + "api_base is required for A2A provider. " + "Either provide api_base parameter, set A2A_API_BASE environment variable, " + "or register the agent in the proxy with model='a2a/'." + ) + + headers = headers or litellm.headers + + response = base_llm_http_handler.completion( + model=model, + stream=stream, + messages=messages, + acompletion=acompletion, + api_base=api_base, + model_response=model_response, + optional_params=optional_params, + litellm_params=litellm_params, + shared_session=shared_session, + custom_llm_provider=custom_llm_provider, + timeout=timeout, + headers=headers, + encoding=_get_encoding(), + api_key=api_key, + logging_obj=logging, + client=client, + provider_config=provider_config, + ) elif custom_llm_provider == "gigachat": # GigaChat - Sber AI's LLM (Russia) api_key = ( @@ -2455,6 +2504,20 @@ def completion( # type: ignore # noqa: PLR0915 headers = headers or litellm.headers + # Add GitHub Copilot headers (same as /responses endpoint does) + if custom_llm_provider == "github_copilot": + from litellm.llms.github_copilot.common_utils import ( + get_copilot_default_headers, + ) + from litellm.llms.github_copilot.authenticator import Authenticator + + copilot_auth = Authenticator() + copilot_api_key = copilot_auth.get_api_key() + copilot_headers = get_copilot_default_headers(copilot_api_key) + if extra_headers: + copilot_headers.update(extra_headers) + extra_headers = copilot_headers + if extra_headers is not None: optional_params["extra_headers"] = extra_headers @@ -3113,8 +3176,8 @@ def completion( # type: ignore # noqa: PLR0915 api_key or litellm.api_key or litellm.openrouter_key - or get_secret("OPENROUTER_API_KEY") - or get_secret("OR_API_KEY") + or get_secret_str("OPENROUTER_API_KEY") + or get_secret_str("OR_API_KEY") ) openrouter_site_url = get_secret("OR_SITE_URL") or "https://litellm.ai" @@ -4555,6 +4618,13 @@ def embedding( # noqa: PLR0915 headers = {} if extra_headers is not None: headers.update(extra_headers) + # Inject proxy auth headers if configured + if litellm.proxy_auth is not None: + try: + proxy_headers = litellm.proxy_auth.get_auth_headers() + headers.update(proxy_headers) + except Exception as e: + verbose_logger.warning(f"Failed to get proxy auth headers: {e}") ### CUSTOM MODEL COST ### input_cost_per_token = kwargs.get("input_cost_per_token", None) output_cost_per_token = kwargs.get("output_cost_per_token", None) @@ -4709,11 +4779,11 @@ def embedding( # noqa: PLR0915 litellm_params=litellm_params_dict, ) elif ( - model in litellm.open_ai_embedding_models - or custom_llm_provider == "openai" + custom_llm_provider == "openai" or custom_llm_provider == "together_ai" or custom_llm_provider == "nvidia_nim" or custom_llm_provider == "litellm_proxy" + or (model in litellm.open_ai_embedding_models and custom_llm_provider is None) ): api_base = ( api_base @@ -4884,8 +4954,8 @@ def embedding( # noqa: PLR0915 api_key or litellm.api_key or litellm.openrouter_key - or get_secret("OPENROUTER_API_KEY") - or get_secret("OR_API_KEY") + or get_secret_str("OPENROUTER_API_KEY") + or get_secret_str("OR_API_KEY") ) openrouter_site_url = get_secret("OR_SITE_URL") or "https://litellm.ai" diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 0f84bba941d..4704549e716 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -744,12 +744,13 @@ "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true, - "tool_use_system_prompt_tokens": 346 + "tool_use_system_prompt_tokens": 346, + "supports_native_streaming": true }, "anthropic.claude-3-5-sonnet-20240620-v1:0": { "input_cost_per_token": 3e-06, "litellm_provider": "bedrock", - "max_input_tokens": 200000, + "max_input_tokens": 1000000, "max_output_tokens": 4096, "max_tokens": 4096, "mode": "chat", @@ -758,14 +759,22 @@ "supports_pdf_input": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_vision": true + "supports_vision": true, + "input_cost_per_token_above_200k_tokens": 6e-06, + "output_cost_per_token_above_200k_tokens": 3e-05, + "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06, + "cache_read_input_token_cost_above_200k_tokens": 6e-07, + "cache_creation_input_token_cost_above_1hr": 7.5e-06, + "cache_creation_input_token_cost_above_1hr_above_200k_tokens": 1.5e-05, + "cache_creation_input_token_cost": 3.75e-06, + "cache_read_input_token_cost": 3e-07 }, "anthropic.claude-3-5-sonnet-20241022-v2:0": { "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_token": 3e-06, "litellm_provider": "bedrock", - "max_input_tokens": 200000, + "max_input_tokens": 1000000, "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", @@ -777,7 +786,13 @@ "supports_prompt_caching": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_vision": true + "supports_vision": true, + "input_cost_per_token_above_200k_tokens": 6e-06, + "output_cost_per_token_above_200k_tokens": 3e-05, + "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06, + "cache_read_input_token_cost_above_200k_tokens": 6e-07, + "cache_creation_input_token_cost_above_1hr": 7.5e-06, + "cache_creation_input_token_cost_above_1hr_above_200k_tokens": 1.5e-05 }, "anthropic.claude-3-7-sonnet-20240620-v1:0": { "cache_creation_input_token_cost": 4.5e-06, @@ -948,6 +963,336 @@ "supports_vision": true, "tool_use_system_prompt_tokens": 159 }, + "anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.25e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05, + "cache_read_input_token_cost": 5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1e-06, + "input_cost_per_token": 5e-06, + "input_cost_per_token_above_200k_tokens": 1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "output_cost_per_token_above_200k_tokens": 3.75e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.25e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05, + "cache_read_input_token_cost": 5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1e-06, + "input_cost_per_token": 5e-06, + "input_cost_per_token_above_200k_tokens": 1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "output_cost_per_token_above_200k_tokens": 3.75e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "global.anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.25e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05, + "cache_read_input_token_cost": 5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1e-06, + "input_cost_per_token": 5e-06, + "input_cost_per_token_above_200k_tokens": 1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "output_cost_per_token_above_200k_tokens": 3.75e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "global.anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.25e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05, + "cache_read_input_token_cost": 5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1e-06, + "input_cost_per_token": 5e-06, + "input_cost_per_token_above_200k_tokens": 1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "output_cost_per_token_above_200k_tokens": 3.75e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "us.anthropic.claude-opus-4-6-v1:0": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "us.anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "eu.anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "eu.anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "apac.anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "apac.anthropic.claude-opus-4-6-v1": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "au.anthropic.claude-opus-4-6-v1:0": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "bedrock_converse", + "max_input_tokens": 200000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, "anthropic.claude-sonnet-4-20250514-v1:0": { "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, @@ -1429,6 +1774,33 @@ "supports_tool_choice": true, "supports_vision": true }, + "azure_ai/claude-opus-4-6": { + "input_cost_per_token": 5e-06, + "output_cost_per_token": 2.5e-05, + "litellm_provider": "azure_ai", + "max_input_tokens": 200000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "cache_creation_input_token_cost": 6.25e-06, + "cache_creation_input_token_cost_above_1hr": 1e-05, + "cache_read_input_token_cost": 5e-07, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 159 + }, "azure_ai/claude-opus-4-1": { "cache_creation_input_token_cost": 1.875e-05, "cache_creation_input_token_cost_above_1hr": 3e-05, @@ -6715,13 +7087,13 @@ "supports_tool_choice": true }, "cerebras/gpt-oss-120b": { - "input_cost_per_token": 2.5e-07, + "input_cost_per_token": 3.5e-07, "litellm_provider": "cerebras", "max_input_tokens": 131072, "max_output_tokens": 32768, "max_tokens": 32768, "mode": "chat", - "output_cost_per_token": 6.9e-07, + "output_cost_per_token": 7.5e-07, "source": "https://www.cerebras.ai/blog/openai-gpt-oss-120b-runs-fastest-on-cerebras", "supports_function_calling": true, "supports_parallel_function_calling": true, @@ -6739,6 +7111,7 @@ "output_cost_per_token": 8e-07, "source": "https://inference-docs.cerebras.ai/support/pricing", "supports_function_calling": true, + "supports_reasoning": true, "supports_tool_choice": true }, "cerebras/zai-glm-4.6": { @@ -7439,6 +7812,130 @@ "supports_vision": true, "tool_use_system_prompt_tokens": 159 }, + "claude-opus-4-6": { + "cache_creation_input_token_cost": 6.25e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05, + "cache_creation_input_token_cost_above_1hr": 1e-05, + "cache_read_input_token_cost": 5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1e-06, + "input_cost_per_token": 5e-06, + "input_cost_per_token_above_200k_tokens": 1e-05, + "litellm_provider": "anthropic", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "output_cost_per_token_above_200k_tokens": 3.75e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "us/claude-opus-4-6": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_creation_input_token_cost_above_1hr": 1.1e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "anthropic", + "max_input_tokens": 200000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "claude-opus-4-6-20260205": { + "cache_creation_input_token_cost": 6.25e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05, + "cache_creation_input_token_cost_above_1hr": 1e-05, + "cache_read_input_token_cost": 5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1e-06, + "input_cost_per_token": 5e-06, + "input_cost_per_token_above_200k_tokens": 1e-05, + "litellm_provider": "anthropic", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "output_cost_per_token_above_200k_tokens": 3.75e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, + "us/claude-opus-4-6-20260205": { + "cache_creation_input_token_cost": 6.875e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.375e-05, + "cache_creation_input_token_cost_above_1hr": 1.1e-05, + "cache_read_input_token_cost": 5.5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1.1e-06, + "input_cost_per_token": 5.5e-06, + "input_cost_per_token_above_200k_tokens": 1.1e-05, + "litellm_provider": "anthropic", + "max_input_tokens": 200000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.75e-05, + "output_cost_per_token_above_200k_tokens": 4.125e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 + }, "claude-sonnet-4-20250514": { "deprecation_date": "2026-05-14", "cache_creation_input_token_cost": 3.75e-06, @@ -10559,6 +11056,32 @@ "/v1/audio/transcriptions" ] }, + "elevenlabs/eleven_v3": { + "input_cost_per_character": 0.00018, + "litellm_provider": "elevenlabs", + "metadata": { + "calculation": "$0.18/1000 characters (Scale plan pricing, 1 credit per character)", + "notes": "ElevenLabs Eleven v3 - most expressive TTS model with 70+ languages and audio tags support" + }, + "mode": "audio_speech", + "source": "https://elevenlabs.io/pricing", + "supported_endpoints": [ + "/v1/audio/speech" + ] + }, + "elevenlabs/eleven_multilingual_v2": { + "input_cost_per_character": 0.00018, + "litellm_provider": "elevenlabs", + "metadata": { + "calculation": "$0.18/1000 characters (Scale plan pricing, 1 credit per character)", + "notes": "ElevenLabs Eleven Multilingual v2 - default TTS model with 29 languages support" + }, + "mode": "audio_speech", + "source": "https://elevenlabs.io/pricing", + "supported_endpoints": [ + "/v1/audio/speech" + ] + }, "embed-english-light-v2.0": { "input_cost_per_token": 1e-07, "litellm_provider": "cohere", @@ -12835,6 +13358,40 @@ "supports_vision": true, "supports_web_search": true }, + "deep-research-pro-preview-12-2025": { + "input_cost_per_image": 0.0011, + "input_cost_per_token": 2e-06, + "input_cost_per_token_batches": 1e-06, + "litellm_provider": "vertex_ai-language-models", + "max_input_tokens": 65536, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "image_generation", + "output_cost_per_image": 0.134, + "output_cost_per_image_token": 0.00012, + "output_cost_per_token": 1.2e-05, + "output_cost_per_token_batches": 6e-06, + "source": "https://ai.google.dev/gemini-api/docs/pricing", + "supported_endpoints": [ + "/v1/chat/completions", + "/v1/completions", + "/v1/batch" + ], + "supported_modalities": [ + "text", + "image" + ], + "supported_output_modalities": [ + "text", + "image" + ], + "supports_function_calling": false, + "supports_prompt_caching": true, + "supports_response_schema": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_web_search": true + }, "gemini-2.5-flash-lite": { "cache_read_input_token_cost": 1e-08, "input_cost_per_audio_token": 3e-07, @@ -13289,7 +13846,8 @@ "supports_tool_choice": true, "supports_video_input": true, "supports_vision": true, - "supports_web_search": true + "supports_web_search": true, + "supports_native_streaming": true }, "vertex_ai/gemini-3-pro-preview": { "cache_read_input_token_cost": 2e-07, @@ -13337,7 +13895,8 @@ "supports_tool_choice": true, "supports_video_input": true, "supports_vision": true, - "supports_web_search": true + "supports_web_search": true, + "supports_native_streaming": true }, "vertex_ai/gemini-3-flash-preview": { "cache_read_input_token_cost": 5e-08, @@ -13380,7 +13939,8 @@ "supports_tool_choice": true, "supports_video_input": true, "supports_vision": true, - "supports_web_search": true + "supports_web_search": true, + "supports_native_streaming": true }, "gemini-2.5-pro-exp-03-25": { "cache_read_input_token_cost": 1.25e-07, @@ -14747,25 +15307,22 @@ "supports_vision": true, "supports_web_search": true }, - "gemini/gemini-2.5-flash-lite": { - "cache_read_input_token_cost": 1e-08, - "input_cost_per_audio_token": 3e-07, - "input_cost_per_token": 1e-07, + "gemini/deep-research-pro-preview-12-2025": { + "input_cost_per_image": 0.0011, + "input_cost_per_token": 2e-06, + "input_cost_per_token_batches": 1e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, - "max_input_tokens": 1048576, - "max_output_tokens": 65535, - "max_pdf_size_mb": 30, - "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, - "mode": "chat", - "output_cost_per_reasoning_token": 4e-07, - "output_cost_per_token": 4e-07, - "rpm": 15, - "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-lite", + "max_input_tokens": 65536, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "image_generation", + "output_cost_per_image": 0.134, + "output_cost_per_image_token": 0.00012, + "output_cost_per_token": 1.2e-05, + "rpm": 1000, + "tpm": 4000000, + "output_cost_per_token_batches": 6e-06, + "source": "https://ai.google.dev/gemini-api/docs/pricing", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -14773,28 +15330,20 @@ ], "supported_modalities": [ "text", - "image", - "audio", - "video" + "image" ], "supported_output_modalities": [ - "text" + "text", + "image" ], - "supports_audio_output": false, - "supports_function_calling": true, - "supports_parallel_function_calling": true, - "supports_pdf_input": true, + "supports_function_calling": false, "supports_prompt_caching": true, - "supports_reasoning": true, "supports_response_schema": true, "supports_system_messages": true, - "supports_tool_choice": true, - "supports_url_context": true, "supports_vision": true, - "supports_web_search": true, - "tpm": 250000 + "supports_web_search": true }, - "gemini/gemini-2.5-flash-lite-preview-09-2025": { + "gemini/gemini-2.5-flash-lite": { "cache_read_input_token_cost": 1e-08, "input_cost_per_audio_token": 3e-07, "input_cost_per_token": 1e-07, @@ -14812,7 +15361,7 @@ "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, "rpm": 15, - "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-lite", "supported_endpoints": [ "/v1/chat/completions", "/v1/completions", @@ -14841,10 +15390,10 @@ "supports_web_search": true, "tpm": 250000 }, - "gemini/gemini-2.5-flash-preview-09-2025": { - "cache_read_input_token_cost": 7.5e-08, - "input_cost_per_audio_token": 1e-06, - "input_cost_per_token": 3e-07, + "gemini/gemini-2.5-flash-lite-preview-09-2025": { + "cache_read_input_token_cost": 1e-08, + "input_cost_per_audio_token": 3e-07, + "input_cost_per_token": 1e-07, "litellm_provider": "gemini", "max_audio_length_hours": 8.4, "max_audio_per_prompt": 1, @@ -14856,8 +15405,8 @@ "max_video_length": 1, "max_videos_per_prompt": 10, "mode": "chat", - "output_cost_per_reasoning_token": 2.5e-06, - "output_cost_per_token": 2.5e-06, + "output_cost_per_reasoning_token": 4e-07, + "output_cost_per_token": 4e-07, "rpm": 15, "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", "supported_endpoints": [ @@ -14888,7 +15437,7 @@ "supports_web_search": true, "tpm": 250000 }, - "gemini/gemini-flash-latest": { + "gemini/gemini-2.5-flash-preview-09-2025": { "cache_read_input_token_cost": 7.5e-08, "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, @@ -14935,10 +15484,10 @@ "supports_web_search": true, "tpm": 250000 }, - "gemini/gemini-flash-lite-latest": { - "cache_read_input_token_cost": 2.5e-08, - "input_cost_per_audio_token": 3e-07, - "input_cost_per_token": 1e-07, + "gemini/gemini-flash-latest": { + "cache_read_input_token_cost": 7.5e-08, + "input_cost_per_audio_token": 1e-06, + "input_cost_per_token": 3e-07, "litellm_provider": "gemini", "max_audio_length_hours": 8.4, "max_audio_per_prompt": 1, @@ -14950,8 +15499,55 @@ "max_video_length": 1, "max_videos_per_prompt": 10, "mode": "chat", - "output_cost_per_reasoning_token": 4e-07, - "output_cost_per_token": 4e-07, + "output_cost_per_reasoning_token": 2.5e-06, + "output_cost_per_token": 2.5e-06, + "rpm": 15, + "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", + "supported_endpoints": [ + "/v1/chat/completions", + "/v1/completions", + "/v1/batch" + ], + "supported_modalities": [ + "text", + "image", + "audio", + "video" + ], + "supported_output_modalities": [ + "text" + ], + "supports_audio_output": false, + "supports_function_calling": true, + "supports_parallel_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_system_messages": true, + "supports_tool_choice": true, + "supports_url_context": true, + "supports_vision": true, + "supports_web_search": true, + "tpm": 250000 + }, + "gemini/gemini-flash-lite-latest": { + "cache_read_input_token_cost": 2.5e-08, + "input_cost_per_audio_token": 3e-07, + "input_cost_per_token": 1e-07, + "litellm_provider": "gemini", + "max_audio_length_hours": 8.4, + "max_audio_per_prompt": 1, + "max_images_per_prompt": 3000, + "max_input_tokens": 1048576, + "max_output_tokens": 65535, + "max_pdf_size_mb": 30, + "max_tokens": 65535, + "max_video_length": 1, + "max_videos_per_prompt": 10, + "mode": "chat", + "output_cost_per_reasoning_token": 4e-07, + "output_cost_per_token": 4e-07, "rpm": 15, "source": "https://developers.googleblog.com/en/continuing-to-bring-you-our-latest-models-with-an-improved-gemini-2-5-flash-and-flash-lite-release/", "supported_endpoints": [ @@ -15331,6 +15927,7 @@ "supports_url_context": true, "supports_vision": true, "supports_web_search": true, + "supports_native_streaming": true, "tpm": 800000 }, "gemini-3-flash-preview": { @@ -15376,7 +15973,8 @@ "supports_tool_choice": true, "supports_url_context": true, "supports_vision": true, - "supports_web_search": true + "supports_web_search": true, + "supports_native_streaming": true }, "gemini/gemini-2.5-pro-exp-03-25": { "cache_read_input_token_cost": 0.0, @@ -21473,6 +22071,20 @@ "supports_tool_choice": true, "supports_web_search": true }, + "moonshot/kimi-k2.5": { + "cache_read_input_token_cost": 1e-07, + "input_cost_per_token": 6e-07, + "litellm_provider": "moonshot", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 3e-06, + "source": "https://platform.moonshot.ai/docs/pricing/chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_vision": true + }, "moonshot/kimi-latest": { "cache_read_input_token_cost": 1.5e-07, "input_cost_per_token": 2e-06, @@ -24314,6 +24926,31 @@ "supports_tool_choice": true, "supports_function_calling": true }, + "openrouter/qwen/qwen3-235b-a22b-2507": { + "input_cost_per_token": 7.1e-08, + "litellm_provider": "openrouter", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 1e-07, + "source": "https://openrouter.ai/qwen/qwen3-235b-a22b-2507", + "supports_function_calling": true, + "supports_tool_choice": true + }, + "openrouter/qwen/qwen3-235b-a22b-thinking-2507": { + "input_cost_per_token": 1.1e-07, + "litellm_provider": "openrouter", + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "max_tokens": 262144, + "mode": "chat", + "output_cost_per_token": 6e-07, + "source": "https://openrouter.ai/qwen/qwen3-235b-a22b-thinking-2507", + "supports_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true + }, "openrouter/switchpoint/router": { "input_cost_per_token": 8.5e-07, "litellm_provider": "openrouter", @@ -24390,21 +25027,21 @@ "supports_tool_choice": true }, "openrouter/xiaomi/mimo-v2-flash": { - "input_cost_per_token": 9e-08, - "output_cost_per_token": 2.9e-07, - "cache_creation_input_token_cost": 0.0, - "cache_read_input_token_cost": 0.0, - "litellm_provider": "openrouter", - "max_input_tokens": 262144, - "max_output_tokens": 16384, - "max_tokens": 16384, - "mode": "chat", - "supports_function_calling": true, - "supports_tool_choice": true, - "supports_reasoning": true, - "supports_vision": false, - "supports_prompt_caching": false - }, + "input_cost_per_token": 9e-08, + "output_cost_per_token": 2.9e-07, + "cache_creation_input_token_cost": 0.0, + "cache_read_input_token_cost": 0.0, + "litellm_provider": "openrouter", + "max_input_tokens": 262144, + "max_output_tokens": 16384, + "max_tokens": 16384, + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_reasoning": true, + "supports_vision": false, + "supports_prompt_caching": false + }, "openrouter/z-ai/glm-4.7": { "input_cost_per_token": 4e-07, "output_cost_per_token": 1.5e-06, @@ -26319,13 +26956,13 @@ "litellm_provider": "bedrock", "max_input_tokens": 77, "mode": "image_edit", - "output_cost_per_image": 0.40 + "output_cost_per_image": 0.4 }, "stability.stable-creative-upscale-v1:0": { "litellm_provider": "bedrock", "max_input_tokens": 77, "mode": "image_edit", - "output_cost_per_image": 0.60 + "output_cost_per_image": 0.6 }, "stability.stable-fast-upscale-v1:0": { "litellm_provider": "bedrock", @@ -27084,6 +27721,34 @@ "supports_reasoning": true, "supports_tool_choice": true }, + "together_ai/zai-org/GLM-4.7": { + "input_cost_per_token": 4.5e-07, + "litellm_provider": "together_ai", + "max_input_tokens": 200000, + "max_output_tokens": 200000, + "max_tokens": 200000, + "mode": "chat", + "output_cost_per_token": 2e-06, + "source": "https://www.together.ai/models/glm-4-7", + "supports_function_calling": true, + "supports_parallel_function_calling": true, + "supports_reasoning": true, + "supports_tool_choice": true + }, + "together_ai/moonshotai/Kimi-K2.5": { + "input_cost_per_token": 5e-07, + "litellm_provider": "together_ai", + "max_input_tokens": 256000, + "max_output_tokens": 256000, + "max_tokens": 256000, + "mode": "chat", + "output_cost_per_token": 2.8e-06, + "source": "https://www.together.ai/models/kimi-k2-5", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_vision": true, + "supports_reasoning": true + }, "together_ai/moonshotai/Kimi-K2-Instruct-0905": { "input_cost_per_token": 1e-06, "litellm_provider": "together_ai", @@ -27800,7 +28465,9 @@ "max_output_tokens": 16384, "max_tokens": 16384, "mode": "chat", - "output_cost_per_token": 3e-07 + "output_cost_per_token": 3e-07, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/alibaba/qwen3-coder": { "input_cost_per_token": 4e-07, @@ -27809,7 +28476,9 @@ "max_output_tokens": 66536, "max_tokens": 66536, "mode": "chat", - "output_cost_per_token": 1.6e-06 + "output_cost_per_token": 1.6e-06, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/amazon/nova-lite": { "input_cost_per_token": 6e-08, @@ -27818,7 +28487,10 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 2.4e-07 + "output_cost_per_token": 2.4e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_response_schema": true }, "vercel_ai_gateway/amazon/nova-micro": { "input_cost_per_token": 3.5e-08, @@ -27827,7 +28499,9 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 1.4e-07 + "output_cost_per_token": 1.4e-07, + "supports_function_calling": true, + "supports_response_schema": true }, "vercel_ai_gateway/amazon/nova-pro": { "input_cost_per_token": 8e-07, @@ -27836,7 +28510,10 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 3.2e-06 + "output_cost_per_token": 3.2e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_response_schema": true }, "vercel_ai_gateway/amazon/titan-embed-text-v2": { "input_cost_per_token": 2e-08, @@ -27856,7 +28533,11 @@ "max_output_tokens": 4096, "max_tokens": 4096, "mode": "chat", - "output_cost_per_token": 1.25e-06 + "output_cost_per_token": 1.25e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/anthropic/claude-3-opus": { "cache_creation_input_token_cost": 1.875e-05, @@ -27867,7 +28548,11 @@ "max_output_tokens": 4096, "max_tokens": 4096, "mode": "chat", - "output_cost_per_token": 7.5e-05 + "output_cost_per_token": 7.5e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/anthropic/claude-3.5-haiku": { "cache_creation_input_token_cost": 1e-06, @@ -27878,7 +28563,11 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 4e-06 + "output_cost_per_token": 4e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/anthropic/claude-3.5-sonnet": { "cache_creation_input_token_cost": 3.75e-06, @@ -27889,7 +28578,11 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 1.5e-05 + "output_cost_per_token": 1.5e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/anthropic/claude-3.7-sonnet": { "cache_creation_input_token_cost": 3.75e-06, @@ -27900,7 +28593,11 @@ "max_output_tokens": 64000, "max_tokens": 64000, "mode": "chat", - "output_cost_per_token": 1.5e-05 + "output_cost_per_token": 1.5e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/anthropic/claude-4-opus": { "cache_creation_input_token_cost": 1.875e-05, @@ -27911,7 +28608,11 @@ "max_output_tokens": 32000, "max_tokens": 32000, "mode": "chat", - "output_cost_per_token": 7.5e-05 + "output_cost_per_token": 7.5e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/anthropic/claude-4-sonnet": { "cache_creation_input_token_cost": 3.75e-06, @@ -27922,7 +28623,9 @@ "max_output_tokens": 64000, "max_tokens": 64000, "mode": "chat", - "output_cost_per_token": 1.5e-05 + "output_cost_per_token": 1.5e-05, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/cohere/command-a": { "input_cost_per_token": 2.5e-06, @@ -27931,7 +28634,9 @@ "max_output_tokens": 8000, "max_tokens": 8000, "mode": "chat", - "output_cost_per_token": 1e-05 + "output_cost_per_token": 1e-05, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/cohere/command-r": { "input_cost_per_token": 1.5e-07, @@ -27940,7 +28645,9 @@ "max_output_tokens": 4096, "max_tokens": 4096, "mode": "chat", - "output_cost_per_token": 6e-07 + "output_cost_per_token": 6e-07, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/cohere/command-r-plus": { "input_cost_per_token": 2.5e-06, @@ -27949,7 +28656,9 @@ "max_output_tokens": 4096, "max_tokens": 4096, "mode": "chat", - "output_cost_per_token": 1e-05 + "output_cost_per_token": 1e-05, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/cohere/embed-v4.0": { "input_cost_per_token": 1.2e-07, @@ -27967,7 +28676,8 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 2.19e-06 + "output_cost_per_token": 2.19e-06, + "supports_tool_choice": true }, "vercel_ai_gateway/deepseek/deepseek-r1-distill-llama-70b": { "input_cost_per_token": 7.5e-07, @@ -27976,7 +28686,10 @@ "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 9.9e-07 + "output_cost_per_token": 9.9e-07, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/deepseek/deepseek-v3": { "input_cost_per_token": 9e-07, @@ -27985,7 +28698,8 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 9e-07 + "output_cost_per_token": 9e-07, + "supports_tool_choice": true }, "vercel_ai_gateway/google/gemini-2.0-flash": { "deprecation_date": "2026-03-31", @@ -27995,7 +28709,11 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 6e-07 + "output_cost_per_token": 6e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/google/gemini-2.0-flash-lite": { "deprecation_date": "2026-03-31", @@ -28005,7 +28723,11 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 3e-07 + "output_cost_per_token": 3e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/google/gemini-2.5-flash": { "input_cost_per_token": 3e-07, @@ -28014,7 +28736,11 @@ "max_output_tokens": 65536, "max_tokens": 65536, "mode": "chat", - "output_cost_per_token": 2.5e-06 + "output_cost_per_token": 2.5e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/google/gemini-2.5-pro": { "input_cost_per_token": 2.5e-06, @@ -28023,7 +28749,11 @@ "max_output_tokens": 65536, "max_tokens": 65536, "mode": "chat", - "output_cost_per_token": 1e-05 + "output_cost_per_token": 1e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/google/gemini-embedding-001": { "input_cost_per_token": 1.5e-07, @@ -28041,7 +28771,10 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 2e-07 + "output_cost_per_token": 2e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/google/text-embedding-005": { "input_cost_per_token": 2.5e-08, @@ -28077,7 +28810,8 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 7.9e-07 + "output_cost_per_token": 7.9e-07, + "supports_tool_choice": true }, "vercel_ai_gateway/meta/llama-3-8b": { "input_cost_per_token": 5e-08, @@ -28086,7 +28820,8 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 8e-08 + "output_cost_per_token": 8e-08, + "supports_tool_choice": true }, "vercel_ai_gateway/meta/llama-3.1-70b": { "input_cost_per_token": 7.2e-07, @@ -28095,7 +28830,8 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 7.2e-07 + "output_cost_per_token": 7.2e-07, + "supports_tool_choice": true }, "vercel_ai_gateway/meta/llama-3.1-8b": { "input_cost_per_token": 5e-08, @@ -28104,7 +28840,9 @@ "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 8e-08 + "output_cost_per_token": 8e-08, + "supports_function_calling": true, + "supports_response_schema": true }, "vercel_ai_gateway/meta/llama-3.2-11b": { "input_cost_per_token": 1.6e-07, @@ -28113,7 +28851,10 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 1.6e-07 + "output_cost_per_token": 1.6e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/meta/llama-3.2-1b": { "input_cost_per_token": 1e-07, @@ -28131,7 +28872,9 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 1.5e-07 + "output_cost_per_token": 1.5e-07, + "supports_function_calling": true, + "supports_response_schema": true }, "vercel_ai_gateway/meta/llama-3.2-90b": { "input_cost_per_token": 7.2e-07, @@ -28140,7 +28883,10 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 7.2e-07 + "output_cost_per_token": 7.2e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/meta/llama-3.3-70b": { "input_cost_per_token": 7.2e-07, @@ -28149,7 +28895,9 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 7.2e-07 + "output_cost_per_token": 7.2e-07, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/meta/llama-4-maverick": { "input_cost_per_token": 2e-07, @@ -28158,7 +28906,8 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 6e-07 + "output_cost_per_token": 6e-07, + "supports_tool_choice": true }, "vercel_ai_gateway/meta/llama-4-scout": { "input_cost_per_token": 1e-07, @@ -28167,7 +28916,10 @@ "max_output_tokens": 8192, "max_tokens": 8192, "mode": "chat", - "output_cost_per_token": 3e-07 + "output_cost_per_token": 3e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/mistral/codestral": { "input_cost_per_token": 3e-07, @@ -28176,7 +28928,9 @@ "max_output_tokens": 4000, "max_tokens": 4000, "mode": "chat", - "output_cost_per_token": 9e-07 + "output_cost_per_token": 9e-07, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/mistral/codestral-embed": { "input_cost_per_token": 1.5e-07, @@ -28194,7 +28948,10 @@ "max_output_tokens": 128000, "max_tokens": 128000, "mode": "chat", - "output_cost_per_token": 2.8e-07 + "output_cost_per_token": 2.8e-07, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/mistral/magistral-medium": { "input_cost_per_token": 2e-06, @@ -28203,7 +28960,10 @@ "max_output_tokens": 64000, "max_tokens": 64000, "mode": "chat", - "output_cost_per_token": 5e-06 + "output_cost_per_token": 5e-06, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/mistral/magistral-small": { "input_cost_per_token": 5e-07, @@ -28212,7 +28972,8 @@ "max_output_tokens": 64000, "max_tokens": 64000, "mode": "chat", - "output_cost_per_token": 1.5e-06 + "output_cost_per_token": 1.5e-06, + "supports_function_calling": true }, "vercel_ai_gateway/mistral/ministral-3b": { "input_cost_per_token": 4e-08, @@ -28221,7 +28982,9 @@ "max_output_tokens": 4000, "max_tokens": 4000, "mode": "chat", - "output_cost_per_token": 4e-08 + "output_cost_per_token": 4e-08, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/mistral/ministral-8b": { "input_cost_per_token": 1e-07, @@ -28230,7 +28993,10 @@ "max_output_tokens": 4000, "max_tokens": 4000, "mode": "chat", - "output_cost_per_token": 1e-07 + "output_cost_per_token": 1e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/mistral/mistral-embed": { "input_cost_per_token": 1e-07, @@ -28248,7 +29014,9 @@ "max_output_tokens": 4000, "max_tokens": 4000, "mode": "chat", - "output_cost_per_token": 6e-06 + "output_cost_per_token": 6e-06, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/mistral/mistral-saba-24b": { "input_cost_per_token": 7.9e-07, @@ -28266,7 +29034,10 @@ "max_output_tokens": 4000, "max_tokens": 4000, "mode": "chat", - "output_cost_per_token": 3e-07 + "output_cost_per_token": 3e-07, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/mistral/mixtral-8x22b-instruct": { "input_cost_per_token": 1.2e-06, @@ -28275,7 +29046,8 @@ "max_output_tokens": 2048, "max_tokens": 2048, "mode": "chat", - "output_cost_per_token": 1.2e-06 + "output_cost_per_token": 1.2e-06, + "supports_function_calling": true }, "vercel_ai_gateway/mistral/pixtral-12b": { "input_cost_per_token": 1.5e-07, @@ -28284,7 +29056,11 @@ "max_output_tokens": 4000, "max_tokens": 4000, "mode": "chat", - "output_cost_per_token": 1.5e-07 + "output_cost_per_token": 1.5e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/mistral/pixtral-large": { "input_cost_per_token": 2e-06, @@ -28293,7 +29069,11 @@ "max_output_tokens": 4000, "max_tokens": 4000, "mode": "chat", - "output_cost_per_token": 6e-06 + "output_cost_per_token": 6e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/moonshotai/kimi-k2": { "input_cost_per_token": 5.5e-07, @@ -28302,7 +29082,9 @@ "max_output_tokens": 16384, "max_tokens": 16384, "mode": "chat", - "output_cost_per_token": 2.2e-06 + "output_cost_per_token": 2.2e-06, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/morph/morph-v3-fast": { "input_cost_per_token": 8e-07, @@ -28329,7 +29111,9 @@ "max_output_tokens": 4096, "max_tokens": 4096, "mode": "chat", - "output_cost_per_token": 1.5e-06 + "output_cost_per_token": 1.5e-06, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/openai/gpt-3.5-turbo-instruct": { "input_cost_per_token": 1.5e-06, @@ -28347,7 +29131,10 @@ "max_output_tokens": 4096, "max_tokens": 4096, "mode": "chat", - "output_cost_per_token": 3e-05 + "output_cost_per_token": 3e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/openai/gpt-4.1": { "cache_creation_input_token_cost": 0.0, @@ -28358,7 +29145,11 @@ "max_output_tokens": 32768, "max_tokens": 32768, "mode": "chat", - "output_cost_per_token": 8e-06 + "output_cost_per_token": 8e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/gpt-4.1-mini": { "cache_creation_input_token_cost": 0.0, @@ -28369,7 +29160,11 @@ "max_output_tokens": 32768, "max_tokens": 32768, "mode": "chat", - "output_cost_per_token": 1.6e-06 + "output_cost_per_token": 1.6e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/gpt-4.1-nano": { "cache_creation_input_token_cost": 0.0, @@ -28380,7 +29175,11 @@ "max_output_tokens": 32768, "max_tokens": 32768, "mode": "chat", - "output_cost_per_token": 4e-07 + "output_cost_per_token": 4e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/gpt-4o": { "cache_creation_input_token_cost": 0.0, @@ -28391,7 +29190,11 @@ "max_output_tokens": 16384, "max_tokens": 16384, "mode": "chat", - "output_cost_per_token": 1e-05 + "output_cost_per_token": 1e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/gpt-4o-mini": { "cache_creation_input_token_cost": 0.0, @@ -28402,7 +29205,11 @@ "max_output_tokens": 16384, "max_tokens": 16384, "mode": "chat", - "output_cost_per_token": 6e-07 + "output_cost_per_token": 6e-07, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/o1": { "cache_creation_input_token_cost": 0.0, @@ -28413,7 +29220,11 @@ "max_output_tokens": 100000, "max_tokens": 100000, "mode": "chat", - "output_cost_per_token": 6e-05 + "output_cost_per_token": 6e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/o3": { "cache_creation_input_token_cost": 0.0, @@ -28424,7 +29235,11 @@ "max_output_tokens": 100000, "max_tokens": 100000, "mode": "chat", - "output_cost_per_token": 8e-06 + "output_cost_per_token": 8e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/o3-mini": { "cache_creation_input_token_cost": 0.0, @@ -28435,7 +29250,10 @@ "max_output_tokens": 100000, "max_tokens": 100000, "mode": "chat", - "output_cost_per_token": 4.4e-06 + "output_cost_per_token": 4.4e-06, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/o4-mini": { "cache_creation_input_token_cost": 0.0, @@ -28446,7 +29264,11 @@ "max_output_tokens": 100000, "max_tokens": 100000, "mode": "chat", - "output_cost_per_token": 4.4e-06 + "output_cost_per_token": 4.4e-06, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_response_schema": true }, "vercel_ai_gateway/openai/text-embedding-3-large": { "input_cost_per_token": 1.3e-07, @@ -28518,7 +29340,10 @@ "max_output_tokens": 32000, "max_tokens": 32000, "mode": "chat", - "output_cost_per_token": 1.5e-05 + "output_cost_per_token": 1.5e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/vercel/v0-1.5-md": { "input_cost_per_token": 3e-06, @@ -28527,7 +29352,10 @@ "max_output_tokens": 32768, "max_tokens": 32768, "mode": "chat", - "output_cost_per_token": 1.5e-05 + "output_cost_per_token": 1.5e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/xai/grok-2": { "input_cost_per_token": 2e-06, @@ -28536,7 +29364,9 @@ "max_output_tokens": 4000, "max_tokens": 4000, "mode": "chat", - "output_cost_per_token": 1e-05 + "output_cost_per_token": 1e-05, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/xai/grok-2-vision": { "input_cost_per_token": 2e-06, @@ -28545,7 +29375,10 @@ "max_output_tokens": 32768, "max_tokens": 32768, "mode": "chat", - "output_cost_per_token": 1e-05 + "output_cost_per_token": 1e-05, + "supports_vision": true, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/xai/grok-3": { "input_cost_per_token": 3e-06, @@ -28554,7 +29387,9 @@ "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 1.5e-05 + "output_cost_per_token": 1.5e-05, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/xai/grok-3-fast": { "input_cost_per_token": 5e-06, @@ -28563,7 +29398,8 @@ "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 2.5e-05 + "output_cost_per_token": 2.5e-05, + "supports_function_calling": true }, "vercel_ai_gateway/xai/grok-3-mini": { "input_cost_per_token": 3e-07, @@ -28572,7 +29408,9 @@ "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 5e-07 + "output_cost_per_token": 5e-07, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/xai/grok-3-mini-fast": { "input_cost_per_token": 6e-07, @@ -28581,7 +29419,9 @@ "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 4e-06 + "output_cost_per_token": 4e-06, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/xai/grok-4": { "input_cost_per_token": 3e-06, @@ -28590,7 +29430,9 @@ "max_output_tokens": 256000, "max_tokens": 256000, "mode": "chat", - "output_cost_per_token": 1.5e-05 + "output_cost_per_token": 1.5e-05, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/zai/glm-4.5": { "input_cost_per_token": 6e-07, @@ -28599,7 +29441,9 @@ "max_output_tokens": 131072, "max_tokens": 131072, "mode": "chat", - "output_cost_per_token": 2.2e-06 + "output_cost_per_token": 2.2e-06, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/zai/glm-4.5-air": { "input_cost_per_token": 2e-07, @@ -28608,7 +29452,9 @@ "max_output_tokens": 96000, "max_tokens": 96000, "mode": "chat", - "output_cost_per_token": 1.1e-06 + "output_cost_per_token": 1.1e-06, + "supports_function_calling": true, + "supports_tool_choice": true }, "vercel_ai_gateway/zai/glm-4.6": { "litellm_provider": "vercel_ai_gateway", @@ -28676,7 +29522,9 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_response_schema": true, - "supports_tool_choice": true + "supports_tool_choice": true, + "supports_native_streaming": true, + "supports_vision": true }, "vertex_ai/claude-3-5-sonnet": { "input_cost_per_token": 3e-06, @@ -28947,7 +29795,38 @@ "supports_response_schema": true, "supports_tool_choice": true, "supports_vision": true, - "tool_use_system_prompt_tokens": 159 + "tool_use_system_prompt_tokens": 159, + "supports_native_streaming": true + }, + "vertex_ai/claude-opus-4-6": { + "cache_creation_input_token_cost": 6.25e-06, + "cache_creation_input_token_cost_above_200k_tokens": 1.25e-05, + "cache_read_input_token_cost": 5e-07, + "cache_read_input_token_cost_above_200k_tokens": 1e-06, + "input_cost_per_token": 5e-06, + "input_cost_per_token_above_200k_tokens": 1e-05, + "litellm_provider": "vertex_ai-anthropic_models", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 2.5e-05, + "output_cost_per_token_above_200k_tokens": 3.75e-05, + "search_context_cost_per_query": { + "search_context_size_high": 0.01, + "search_context_size_low": 0.01, + "search_context_size_medium": 0.01 + }, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_tool_choice": true, + "supports_vision": true, + "tool_use_system_prompt_tokens": 346 }, "vertex_ai/claude-sonnet-4-5": { "cache_creation_input_token_cost": 3.75e-06, @@ -28999,7 +29878,8 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_vision": true + "supports_vision": true, + "supports_native_streaming": true }, "vertex_ai/claude-opus-4@20250514": { "cache_creation_input_token_cost": 1.875e-05, @@ -29281,6 +30161,21 @@ "output_cost_per_token_batches": 6e-06, "source": "https://docs.cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/3-pro-image" }, + "vertex_ai/deep-research-pro-preview-12-2025": { + "input_cost_per_image": 0.0011, + "input_cost_per_token": 2e-06, + "input_cost_per_token_batches": 1e-06, + "litellm_provider": "vertex_ai-language-models", + "max_input_tokens": 65536, + "max_output_tokens": 32768, + "max_tokens": 32768, + "mode": "image_generation", + "output_cost_per_image": 0.134, + "output_cost_per_image_token": 0.00012, + "output_cost_per_token": 1.2e-05, + "output_cost_per_token_batches": 6e-06, + "source": "https://docs.cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/3-pro-image" + }, "vertex_ai/imagegeneration@006": { "litellm_provider": "vertex_ai-image-models", "mode": "image_generation", @@ -29770,6 +30665,9 @@ "mode": "chat", "output_cost_per_token": 1e-06, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", + "supported_regions": [ + "global" + ], "supports_function_calling": true, "supports_tool_choice": true }, @@ -29782,6 +30680,9 @@ "mode": "chat", "output_cost_per_token": 4e-06, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", + "supported_regions": [ + "global" + ], "supports_function_calling": true, "supports_tool_choice": true }, @@ -29794,6 +30695,9 @@ "mode": "chat", "output_cost_per_token": 1.2e-06, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", + "supported_regions": [ + "global" + ], "supports_function_calling": true, "supports_tool_choice": true }, @@ -29806,6 +30710,9 @@ "mode": "chat", "output_cost_per_token": 1.2e-06, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", + "supported_regions": [ + "global" + ], "supports_function_calling": true, "supports_tool_choice": true }, @@ -34754,4 +35661,4 @@ "output_cost_per_token": 0, "supports_reasoning": true } -} \ No newline at end of file +} diff --git a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py index 081d83dd1c8..75b75d3ba44 100644 --- a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py +++ b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py @@ -27,6 +27,7 @@ def __init__( oauth2_headers: Optional[Dict[str, str]] = None, mcp_protocol_version: Optional[str] = None, raw_headers: Optional[Dict[str, str]] = None, + client_ip: Optional[str] = None, ): self.user_api_key_auth = user_api_key_auth self.mcp_auth_header = mcp_auth_header @@ -35,3 +36,4 @@ def __init__( self.mcp_protocol_version = mcp_protocol_version self.oauth2_headers = oauth2_headers self.raw_headers = raw_headers + self.client_ip = client_ip diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py index 49d6ac7d898..786cfbfb008 100644 --- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py +++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py @@ -1,11 +1,12 @@ from typing import Dict, List, Optional, Set, Tuple +from fastapi import HTTPException from starlette.datastructures import Headers from starlette.requests import Request from starlette.types import Scope from litellm._logging import verbose_logger -from litellm.proxy._types import LiteLLM_TeamTable, SpecialHeaders, UserAPIKeyAuth +from litellm.proxy._types import LiteLLM_TeamTable, ProxyException, SpecialHeaders, UserAPIKeyAuth from litellm.proxy.auth.user_api_key_auth import user_api_key_auth @@ -63,6 +64,13 @@ async def process_mcp_request( HTTPException: If headers are invalid or missing required headers """ headers = MCPRequestHandler._safe_get_headers_from_scope(scope) + + # Check if there is an explicit LiteLLM API key (primary header) + has_explicit_litellm_key = ( + headers.get(MCPRequestHandler.LITELLM_API_KEY_HEADER_NAME_PRIMARY) + is not None + ) + litellm_api_key = ( MCPRequestHandler.get_litellm_api_key_from_headers(headers) or "" ) @@ -106,16 +114,38 @@ async def mock_body(): request.body = mock_body # type: ignore if ".well-known" in str(request.url): # public routes validated_user_api_key_auth = UserAPIKeyAuth() - # elif litellm_api_key == "": - # from fastapi import HTTPException - - # raise HTTPException( - # status_code=401, - # detail="LiteLLM API key is missing. Please add it or use OAuth authentication.", - # headers={ - # "WWW-Authenticate": f'Bearer resource_metadata=f"{request.base_url}/.well-known/oauth-protected-resource"', - # }, - # ) + elif has_explicit_litellm_key: + # Explicit x-litellm-api-key provided - always validate normally + validated_user_api_key_auth = await user_api_key_auth( + api_key=litellm_api_key, request=request + ) + elif oauth2_headers: + # No x-litellm-api-key, but Authorization header present. + # Could be a LiteLLM key (backward compat) OR an OAuth2 token + # from an upstream MCP provider (e.g. Atlassian). + # Try LiteLLM auth first; on auth failure, treat as OAuth2 passthrough. + try: + validated_user_api_key_auth = await user_api_key_auth( + api_key=litellm_api_key, request=request + ) + except HTTPException as e: + if e.status_code in (401, 403): + verbose_logger.debug( + "MCP OAuth2: Authorization header is not a valid LiteLLM key, " + "treating as OAuth2 token passthrough" + ) + validated_user_api_key_auth = UserAPIKeyAuth() + else: + raise + except ProxyException as e: + if str(e.code) in ("401", "403"): + verbose_logger.debug( + "MCP OAuth2: Authorization header is not a valid LiteLLM key, " + "treating as OAuth2 token passthrough" + ) + validated_user_api_key_auth = UserAPIKeyAuth() + else: + raise else: validated_user_api_key_auth = await user_api_key_auth( api_key=litellm_api_key, request=request @@ -387,6 +417,9 @@ async def _get_team_object_permission( user_api_key_cache, ) + verbose_logger.debug( + f"MCP team permission lookup: team_id={user_api_key_auth.team_id if user_api_key_auth else None}" + ) if not user_api_key_auth or not user_api_key_auth.team_id or not prisma_client: return None diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py index 56feff548ad..8b052dd0da1 100644 --- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py @@ -9,13 +9,14 @@ get_async_httpx_client, httpxSpecialProvider, ) +from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.proxy.common_utils.encrypt_decrypt_utils import ( decrypt_value_helper, encrypt_value_helper, ) from litellm.proxy.common_utils.http_parsing_utils import _read_request_body -from litellm.types.mcp_server.mcp_server_manager import MCPServer from litellm.proxy.utils import get_server_root_path +from litellm.types.mcp_server.mcp_server_manager import MCPServer router = APIRouter( tags=["mcp"], @@ -300,7 +301,10 @@ async def authorize( ) lookup_name = mcp_server_name or client_id - mcp_server = global_mcp_server_manager.get_mcp_server_by_name(lookup_name) + client_ip = IPAddressUtils.get_mcp_client_ip(request) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name( + lookup_name, client_ip=client_ip + ) if mcp_server is None: raise HTTPException(status_code=404, detail="MCP server not found") return await authorize_with_server( @@ -342,7 +346,10 @@ async def token_endpoint( ) lookup_name = mcp_server_name or client_id - mcp_server = global_mcp_server_manager.get_mcp_server_by_name(lookup_name) + client_ip = IPAddressUtils.get_mcp_client_ip(request) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name( + lookup_name, client_ip=client_ip + ) if mcp_server is None: raise HTTPException(status_code=404, detail="MCP server not found") return await exchange_token_with_server( @@ -425,7 +432,10 @@ def _build_oauth_protected_resource_response( request_base_url = get_request_base_url(request) mcp_server: Optional[MCPServer] = None if mcp_server_name: - mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name) + client_ip = IPAddressUtils.get_mcp_client_ip(request) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name( + mcp_server_name, client_ip=client_ip + ) # Build resource URL based on the pattern if mcp_server_name: @@ -538,7 +548,10 @@ def _build_oauth_authorization_server_response( mcp_server: Optional[MCPServer] = None if mcp_server_name: - mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name) + client_ip = IPAddressUtils.get_mcp_client_ip(request) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name( + mcp_server_name, client_ip=client_ip + ) return { "issuer": request_base_url, # point to your proxy @@ -629,7 +642,10 @@ async def register_client(request: Request, mcp_server_name: Optional[str] = Non if not mcp_server_name: return dummy_return - mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name) + client_ip = IPAddressUtils.get_mcp_client_ip(request) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name( + mcp_server_name, client_ip=client_ip + ) if mcp_server is None: return dummy_return return await register_client_with_server( diff --git a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py index 4d53ae7059d..14bbb82808d 100644 --- a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py +++ b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py @@ -1,26 +1,37 @@ """ MCP Guardrail Handler for Unified Guardrails. -This handler works with the synthetic "messages" payload generated by -`ProxyLogging._convert_mcp_to_llm_format`, which always produces a single user -message whose `content` string encodes the MCP tool name and arguments. The -handler simply feeds that text through the configured guardrail and writes the -result back onto the message. +Converts an MCP call_tool (name + arguments) into a single OpenAI-compatible +tool_call and passes it to apply_guardrail. Works with the synthetic payload +from ProxyLogging._convert_mcp_to_llm_format. + +Note: For MCP tool definitions (schema) -> OpenAI tools=[], see +litellm.experimental_mcp_client.tools.transform_mcp_tool_to_openai_tool +when you have a full MCP Tool from list_tools. Here we only have the call +payload (name + arguments) so we just build the tool_call. """ from typing import TYPE_CHECKING, Any, Dict, Optional +from mcp.types import Tool as MCPTool + from litellm._logging import verbose_proxy_logger +from litellm.experimental_mcp_client.tools import transform_mcp_tool_to_openai_tool from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation +from litellm.types.llms.openai import ( + ChatCompletionToolParam, + ChatCompletionToolParamFunctionChunk, +) from litellm.types.utils import GenericGuardrailAPIInputs if TYPE_CHECKING: - from litellm.integrations.custom_guardrail import CustomGuardrail from mcp.types import CallToolResult + from litellm.integrations.custom_guardrail import CustomGuardrail + class MCPGuardrailTranslationHandler(BaseTranslation): - """Guardrail translation handler for MCP tool calls.""" + """Guardrail translation handler for MCP tool calls (passes a single tool_call to guardrail).""" async def process_input_messages( self, @@ -28,56 +39,51 @@ async def process_input_messages( guardrail_to_apply: "CustomGuardrail", litellm_logging_obj: Optional[Any] = None, ) -> Dict[str, Any]: - messages = data.get("messages") - if not isinstance(messages, list) or not messages: - verbose_proxy_logger.debug("MCP Guardrail: No messages to process") - return data - - first_message = messages[0] - content: Optional[str] = None - if isinstance(first_message, dict): - content = first_message.get("content") - else: - content = getattr(first_message, "content", None) + mcp_tool_name = data.get("mcp_tool_name") or data.get("name") + mcp_arguments = data.get("mcp_arguments") or data.get("arguments") + mcp_tool_description = data.get("mcp_tool_description") or data.get( + "description" + ) + if mcp_arguments is None or not isinstance(mcp_arguments, dict): + mcp_arguments = {} - if not isinstance(content, str): - verbose_proxy_logger.debug( - "MCP Guardrail: Message content missing or not a string", - ) + if not mcp_tool_name: + verbose_proxy_logger.debug("MCP Guardrail: mcp_tool_name missing") return data - inputs = GenericGuardrailAPIInputs(texts=[content]) - # Include model information if available - model = data.get("model") - if model: - inputs["model"] = model - guardrailed_inputs = await guardrail_to_apply.apply_guardrail( + # Convert MCP input via transform_mcp_tool_to_openai_tool, then map to litellm + # ChatCompletionToolParam (openai SDK type has incompatible strict/cache_control). + mcp_tool = MCPTool( + name=mcp_tool_name, + description=mcp_tool_description or "", + inputSchema={}, # Call payload has no schema; guardrail gets args from request_data + ) + openai_tool = transform_mcp_tool_to_openai_tool(mcp_tool) + fn = openai_tool["function"] + tool_def: ChatCompletionToolParam = { + "type": "function", + "function": ChatCompletionToolParamFunctionChunk( + name=fn["name"], + description=fn.get("description") or "", + parameters=fn.get("parameters") + or { + "type": "object", + "properties": {}, + "additionalProperties": False, + }, + strict=fn.get("strict", False) or False, # Default to False if None + ), + } + inputs: GenericGuardrailAPIInputs = GenericGuardrailAPIInputs( + tools=[tool_def], + ) + + await guardrail_to_apply.apply_guardrail( inputs=inputs, request_data=data, input_type="request", logging_obj=litellm_logging_obj, ) - guardrailed_texts = ( - guardrailed_inputs.get("texts", []) if guardrailed_inputs else [] - ) - - if guardrailed_texts: - new_content = guardrailed_texts[0] - if isinstance(first_message, dict): - first_message["content"] = new_content - else: - setattr(first_message, "content", new_content) - - verbose_proxy_logger.debug( - "MCP Guardrail: Updated content for tool %s", - data.get("mcp_tool_name"), - ) - else: - verbose_proxy_logger.debug( - "MCP Guardrail: Guardrail returned no text updates for tool %s", - data.get("mcp_tool_name"), - ) - return data async def process_output_response( @@ -87,7 +93,6 @@ async def process_output_response( litellm_logging_obj: Optional[Any] = None, user_api_key_dict: Optional[Any] = None, ) -> Any: - # Not implemented: MCP guardrail translation never calls this path today. verbose_proxy_logger.debug( "MCP Guardrail: Output processing not implemented for MCP tools", ) diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py index 4c17a2ff3e0..e7174f943b2 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py @@ -53,6 +53,7 @@ MCPTransportType, UserAPIKeyAuth, ) +from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.proxy.common_utils.encrypt_decrypt_utils import decrypt_value_helper from litellm.proxy.utils import ProxyLogging from litellm.types.llms.custom_http import httpxSpecialProvider @@ -65,20 +66,23 @@ from litellm.types.utils import CallTypes try: - from mcp.shared.tool_name_validation import ( # type: ignore + from mcp.shared.tool_name_validation import ( + validate_tool_name, # pyright: ignore[reportAssignmentType] + ) + from mcp.shared.tool_name_validation import ( SEP_986_URL, - validate_tool_name, ) except ImportError: from pydantic import BaseModel + SEP_986_URL = "https://github.com/modelcontextprotocol/protocol/blob/main/proposals/0001-tool-name-validation.md" - class ToolNameValidationResult(BaseModel): + class _ToolNameValidationResult(BaseModel): is_valid: bool = True warnings: list = [] - def validate_tool_name(name: str) -> ToolNameValidationResult: # type: ignore[misc] - return ToolNameValidationResult() + def validate_tool_name(name: str) -> _ToolNameValidationResult: # type: ignore[misc] + return _ToolNameValidationResult() # Probe includes characters on both sides of the separator to mimic real prefixed tool names. @@ -324,6 +328,9 @@ async def load_servers_from_config( access_groups=server_config.get("access_groups", None), static_headers=server_config.get("static_headers", None), allow_all_keys=bool(server_config.get("allow_all_keys", False)), + available_on_public_internet=bool( + server_config.get("available_on_public_internet", False) + ), ) self.config_mcp_servers[server_id] = new_server @@ -469,12 +476,12 @@ def _register_openapi_tools(self, spec_path: str, server: MCPServer, base_url: s ) # Update tool name to server name mapping (for both prefixed and base names) - self.tool_name_to_mcp_server_name_mapping[ - base_tool_name - ] = server_prefix - self.tool_name_to_mcp_server_name_mapping[ - prefixed_tool_name - ] = server_prefix + self.tool_name_to_mcp_server_name_mapping[base_tool_name] = ( + server_prefix + ) + self.tool_name_to_mcp_server_name_mapping[prefixed_tool_name] = ( + server_prefix + ) registered_count += 1 verbose_logger.debug( @@ -622,6 +629,9 @@ async def build_mcp_server_from_table( allowed_tools=getattr(mcp_server, "allowed_tools", None), disallowed_tools=getattr(mcp_server, "disallowed_tools", None), allow_all_keys=mcp_server.allow_all_keys, + available_on_public_internet=bool( + getattr(mcp_server, "available_on_public_internet", False) + ), updated_at=getattr(mcp_server, "updated_at", None), ) return new_server @@ -696,6 +706,23 @@ async def get_allowed_mcp_servers( verbose_logger.warning(f"Failed to get allowed MCP servers: {str(e)}.") return allow_all_server_ids + def filter_server_ids_by_ip( + self, server_ids: List[str], client_ip: Optional[str] + ) -> List[str]: + """ + Filter server IDs by client IP — external callers only see public servers. + + Returns server_ids unchanged when client_ip is None (no filtering). + """ + if client_ip is None: + return server_ids + return [ + sid + for sid in server_ids + if (s := self.get_mcp_server_by_id(sid)) is not None + and self._is_server_accessible_from_ip(s, client_ip) + ] + async def get_tools_for_server(self, server_id: str) -> List[MCPTool]: """ Get the tools for a given server @@ -1929,7 +1956,9 @@ async def _call_regular_mcp_tool( ) async def _call_tool_via_client(client, params): - return await client.call_tool(params, host_progress_callback=host_progress_callback) + return await client.call_tool( + params, host_progress_callback=host_progress_callback + ) tasks.append( asyncio.create_task(_call_tool_via_client(client, call_tool_params)) @@ -1967,7 +1996,6 @@ async def call_tool( oauth2_headers: Optional[Dict[str, str]] = None, raw_headers: Optional[Dict[str, str]] = None, host_progress_callback: Optional[Callable] = None, - ) -> CallToolResult: """ Call a tool with the given name and arguments @@ -2200,6 +2228,42 @@ def get_mcp_servers_from_ids(self, server_ids: List[str]) -> List[MCPServer]: servers.append(server) return servers + def _get_general_settings(self) -> Dict[str, Any]: + """Get general_settings, importing lazily to avoid circular imports.""" + try: + from litellm.proxy.proxy_server import ( + general_settings as proxy_general_settings, + ) + return proxy_general_settings + except ImportError: + # Fallback if proxy_server not available + return {} + + def _is_server_accessible_from_ip( + self, server: MCPServer, client_ip: Optional[str] + ) -> bool: + """ + Check if a server is accessible from the given client IP. + + - If client_ip is None, no IP filtering is applied (internal callers). + - If the server has available_on_public_internet=True, it's always accessible. + - Otherwise, only internal/private IPs can access it. + """ + if client_ip is None: + return True + if server.available_on_public_internet: + return True + # Check backwards compat: litellm.public_mcp_servers + public_ids = set(litellm.public_mcp_servers or []) + if server.server_id in public_ids: + return True + # Non-public server: only accessible from internal IPs + general_settings = self._get_general_settings() + internal_networks = IPAddressUtils.parse_internal_networks( + general_settings.get("mcp_internal_ip_ranges") + ) + return IPAddressUtils.is_internal_ip(client_ip, internal_networks) + def get_mcp_server_by_id(self, server_id: str) -> Optional[MCPServer]: """ Get the MCP Server from the server id @@ -2212,27 +2276,72 @@ def get_mcp_server_by_id(self, server_id: str) -> Optional[MCPServer]: def get_public_mcp_servers(self) -> List[MCPServer]: """ - Get the public MCP servers + Get the public MCP servers (available_on_public_internet=True flag on server). + Also includes servers from litellm.public_mcp_servers for backwards compat. """ servers: List[MCPServer] = [] - if litellm.public_mcp_servers is None: - return servers - for server_id in litellm.public_mcp_servers: - server = self.get_mcp_server_by_id(server_id) - if server: + public_ids = set(litellm.public_mcp_servers or []) + for server in self.get_registry().values(): + if server.available_on_public_internet or server.server_id in public_ids: servers.append(server) return servers - def get_mcp_server_by_name(self, server_name: str) -> Optional[MCPServer]: + def get_mcp_server_by_name( + self, server_name: str, client_ip: Optional[str] = None + ) -> Optional[MCPServer]: """ - Get the MCP Server from the server name + Get the MCP Server from the server name. + + Uses priority-based matching to avoid collisions: + 1. First pass: exact alias match (highest priority) + 2. Second pass: exact server_name match + 3. Third pass: exact name match (lowest priority) + + Args: + server_name: The server name to look up. + client_ip: Optional client IP for access control. When provided, + non-public servers are hidden from external IPs. """ registry = self.get_registry() + # Pass 1: Match by alias (highest priority) + for server in registry.values(): + if server.alias == server_name: + if not self._is_server_accessible_from_ip(server, client_ip): + return None + return server + # Pass 2: Match by server_name for server in registry.values(): if server.server_name == server_name: + if not self._is_server_accessible_from_ip(server, client_ip): + return None + return server + # Pass 3: Match by name (lowest priority) + for server in registry.values(): + if server.name == server_name: + if not self._is_server_accessible_from_ip(server, client_ip): + return None return server return None + def get_filtered_registry( + self, client_ip: Optional[str] = None + ) -> Dict[str, MCPServer]: + """ + Get registry filtered by client IP access control. + + Args: + client_ip: Optional client IP. When provided, non-public servers + are hidden from external IPs. When None, returns all servers. + """ + registry = self.get_registry() + if client_ip is None: + return registry + return { + k: v + for k, v in registry.items() + if self._is_server_accessible_from_ip(v, client_ip) + } + def _generate_stable_server_id( self, server_name: str, @@ -2462,6 +2571,7 @@ def _build_mcp_server_table(self, server: MCPServer) -> LiteLLM_MCPServerTable: token_url=server.token_url, registration_url=server.registration_url, allow_all_keys=server.allow_all_keys, + available_on_public_internet=server.available_on_public_internet, ) async def get_all_mcp_servers_unfiltered(self) -> List[LiteLLM_MCPServerTable]: diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py index d93f852f22d..2cd56e0ff3f 100644 --- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py @@ -10,8 +10,10 @@ ) from litellm.proxy._experimental.mcp_server.utils import merge_mcp_headers from litellm.proxy._types import UserAPIKeyAuth +from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.proxy.auth.user_api_key_auth import user_api_key_auth from litellm.types.mcp import MCPAuth +from litellm.types.utils import CallTypes MCP_AVAILABLE: bool = True try: @@ -28,6 +30,7 @@ if MCP_AVAILABLE: from mcp.types import Tool as MCPTool + from litellm.proxy._experimental.mcp_server.mcp_server_manager import ( global_mcp_server_manager, ) @@ -76,6 +79,26 @@ def _create_tool_response_objects(tools, server_mcp_info): for tool in tools ] + def _extract_mcp_headers_from_request( + request: Request, + mcp_request_handler_cls, + ) -> tuple: + """ + Extract MCP auth headers from HTTP request. + + Returns: + Tuple of (mcp_auth_header, mcp_server_auth_headers, raw_headers) + """ + headers = request.headers + raw_headers = dict(headers) + mcp_auth_header = mcp_request_handler_cls._get_mcp_auth_header_from_headers( + headers + ) + mcp_server_auth_headers = ( + mcp_request_handler_cls._get_mcp_server_auth_headers_from_headers(headers) + ) + return mcp_auth_header, mcp_server_auth_headers, raw_headers + async def _get_tools_for_single_server( server, server_auth_header, @@ -96,6 +119,35 @@ async def _get_tools_for_single_server( return _create_tool_response_objects(tools, server.mcp_info) + async def _resolve_allowed_mcp_servers_for_tool_call( + user_api_key_dict: UserAPIKeyAuth, + server_id: str, + ) -> List[MCPServer]: + """Resolve allowed MCP servers for the given user and validate server_id access.""" + auth_contexts = await build_effective_auth_contexts(user_api_key_dict) + allowed_server_ids_set = set() + for auth_context in auth_contexts: + servers = await global_mcp_server_manager.get_allowed_mcp_servers( + user_api_key_auth=auth_context + ) + allowed_server_ids_set.update(servers) + if server_id not in allowed_server_ids_set: + raise HTTPException( + status_code=403, + detail={ + "error": "access_denied", + "message": f"The key is not allowed to access server {server_id}", + }, + ) + allowed_mcp_servers: List[MCPServer] = [] + for allowed_server_id in allowed_server_ids_set: + server = global_mcp_server_manager.get_mcp_server_by_id( + allowed_server_id + ) + if server is not None: + allowed_mcp_servers.append(server) + return allowed_mcp_servers + ######################################################## @router.get("/tools/list", dependencies=[Depends(user_api_key_auth)]) async def list_tool_rest_api( @@ -142,21 +194,25 @@ async def list_tool_rest_api( auth_contexts = await build_effective_auth_contexts(user_api_key_dict) + _rest_client_ip = IPAddressUtils.get_mcp_client_ip(request) + allowed_server_ids_set = set() for auth_context in auth_contexts: servers = await global_mcp_server_manager.get_allowed_mcp_servers( - user_api_key_auth=auth_context + user_api_key_auth=auth_context, ) allowed_server_ids_set.update(servers) - allowed_server_ids = list(allowed_server_ids_set) + allowed_server_ids = global_mcp_server_manager.filter_server_ids_by_ip( + list(allowed_server_ids_set), _rest_client_ip + ) list_tools_result = [] error_message = None # If server_id is specified, only query that specific server if server_id: - if server_id not in allowed_server_ids_set: + if server_id not in allowed_server_ids: raise HTTPException( status_code=403, detail={ @@ -164,7 +220,9 @@ async def list_tool_rest_api( "message": f"The key is not allowed to access server {server_id}", }, ) - server = global_mcp_server_manager.get_mcp_server_by_id(server_id) + server = global_mcp_server_manager.get_mcp_server_by_id( + server_id + ) if server is None: return { "tools": [], @@ -261,7 +319,14 @@ async def call_tool_rest_api( from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import ( MCPRequestHandler, ) - from litellm.proxy.proxy_server import add_litellm_data_to_request, proxy_config + from litellm.proxy.common_request_processing import ( + ProxyBaseLLMRequestProcessing, + ) + from litellm.proxy.proxy_server import ( + general_settings, + proxy_config, + proxy_logging_obj, + ) try: data = await request.json() @@ -289,28 +354,22 @@ async def call_tool_rest_api( tool_arguments = data.get("arguments") - data = await add_litellm_data_to_request( - data=data, - request=request, - user_api_key_dict=user_api_key_dict, - proxy_config=proxy_config, + proxy_base_llm_response_processor = ProxyBaseLLMRequestProcessing(data=data) + data, logging_obj = ( + await proxy_base_llm_response_processor.common_processing_pre_call_logic( + request=request, + user_api_key_dict=user_api_key_dict, + proxy_config=proxy_config, + route_type=CallTypes.call_mcp_tool.value, + proxy_logging_obj=proxy_logging_obj, + general_settings=general_settings, + ) ) - # FIX: Extract MCP auth headers from request - # The UI sends bearer token in x-mcp-auth header and server-specific headers, - # but they weren't being extracted and passed to call_mcp_tool. - # This fix ensures auth headers are properly extracted from the HTTP request - # and passed through to the MCP server for authentication. - headers = request.headers - raw_headers_from_request = dict(headers) - mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers( - headers - ) - mcp_server_auth_headers = ( - MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers) + # Extract MCP auth headers from request and add to data dict + mcp_auth_header, mcp_server_auth_headers, raw_headers_from_request = ( + _extract_mcp_headers_from_request(request, MCPRequestHandler) ) - - # Add extracted headers to data dict to pass to call_mcp_tool if mcp_auth_header: data["mcp_auth_header"] = mcp_auth_header if mcp_server_auth_headers: @@ -325,14 +384,21 @@ async def call_tool_rest_api( # Get all auth contexts auth_contexts = await build_effective_auth_contexts(user_api_key_dict) - # Collect allowed server IDs from all contexts + # Collect allowed server IDs from all contexts, then apply IP filtering + _rest_client_ip = IPAddressUtils.get_mcp_client_ip(request) allowed_server_ids_set = set() for auth_context in auth_contexts: servers = await global_mcp_server_manager.get_allowed_mcp_servers( - user_api_key_auth=auth_context + user_api_key_auth=auth_context, ) allowed_server_ids_set.update(servers) + allowed_server_ids_set = set( + global_mcp_server_manager.filter_server_ids_by_ip( + list(allowed_server_ids_set), _rest_client_ip + ) + ) + # Check if the specified server_id is allowed if server_id not in allowed_server_ids_set: raise HTTPException( diff --git a/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py new file mode 100644 index 00000000000..e5cb6a0098d --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py @@ -0,0 +1,250 @@ +""" +Semantic MCP Tool Filtering using semantic-router + +Filters MCP tools semantically for /chat/completions and /responses endpoints. +""" +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from litellm._logging import verbose_logger + +if TYPE_CHECKING: + from semantic_router.routers import SemanticRouter + + from litellm.router import Router + + +class SemanticMCPToolFilter: + """Filters MCP tools using semantic similarity to reduce context window size.""" + + def __init__( + self, + embedding_model: str, + litellm_router_instance: "Router", + top_k: int = 10, + similarity_threshold: float = 0.3, + enabled: bool = True, + ): + """ + Initialize the semantic tool filter. + + Args: + embedding_model: Model to use for embeddings (e.g., "text-embedding-3-small") + litellm_router_instance: Router instance for embedding generation + top_k: Maximum number of tools to return + similarity_threshold: Minimum similarity score for filtering + enabled: Whether filtering is enabled + """ + self.enabled = enabled + self.top_k = top_k + self.similarity_threshold = similarity_threshold + self.embedding_model = embedding_model + self.router_instance = litellm_router_instance + self.tool_router: Optional["SemanticRouter"] = None + self._tool_map: Dict[str, Any] = {} # MCPTool objects or OpenAI function dicts + + async def build_router_from_mcp_registry(self) -> None: + """Build semantic router from all MCP tools in the registry (no auth checks).""" + from litellm.proxy._experimental.mcp_server.mcp_server_manager import ( + global_mcp_server_manager, + ) + + try: + # Get all servers from registry without auth checks + registry = global_mcp_server_manager.get_registry() + if not registry: + verbose_logger.warning("MCP registry is empty") + self.tool_router = None + return + + # Fetch tools from all servers in parallel + all_tools = [] + for server_id, server in registry.items(): + try: + tools = await global_mcp_server_manager.get_tools_for_server(server_id) + all_tools.extend(tools) + except Exception as e: + verbose_logger.warning(f"Failed to fetch tools from server {server_id}: {e}") + continue + + if not all_tools: + verbose_logger.warning("No MCP tools found in registry") + self.tool_router = None + return + + verbose_logger.info(f"Fetched {len(all_tools)} tools from {len(registry)} MCP servers") + self._build_router(all_tools) + + except Exception as e: + verbose_logger.error(f"Failed to build router from MCP registry: {e}") + self.tool_router = None + raise + + def _extract_tool_info(self, tool) -> tuple[str, str]: + """Extract name and description from MCP tool or OpenAI function dict.""" + name: str + description: str + + if isinstance(tool, dict): + # OpenAI function format + name = tool.get("name", "") + description = tool.get("description", name) + else: + # MCPTool object + name = str(tool.name) + description = str(tool.description) if tool.description else str(tool.name) + + return name, description + + def _build_router(self, tools: List) -> None: + """Build semantic router with tools (MCPTool objects or OpenAI function dicts).""" + from semantic_router.routers import SemanticRouter + from semantic_router.routers.base import Route + + from litellm.router_strategy.auto_router.litellm_encoder import ( + LiteLLMRouterEncoder, + ) + + if not tools: + self.tool_router = None + return + + try: + # Convert tools to routes + routes = [] + self._tool_map = {} + + for tool in tools: + name, description = self._extract_tool_info(tool) + self._tool_map[name] = tool + + routes.append( + Route( + name=name, + description=description, + utterances=[description], + score_threshold=self.similarity_threshold, + ) + ) + + self.tool_router = SemanticRouter( + routes=routes, + encoder=LiteLLMRouterEncoder( + litellm_router_instance=self.router_instance, + model_name=self.embedding_model, + score_threshold=self.similarity_threshold, + ), + auto_sync="local", + ) + + verbose_logger.info( + f"Built semantic router with {len(routes)} tools" + ) + + except Exception as e: + verbose_logger.error(f"Failed to build semantic router: {e}") + self.tool_router = None + raise + + async def filter_tools( + self, + query: str, + available_tools: List[Any], + top_k: Optional[int] = None, + ) -> List[Any]: + """ + Filter tools semantically based on query. + + Args: + query: User query to match against tools + available_tools: Full list of available MCP tools + top_k: Override default top_k (optional) + + Returns: + Filtered and ordered list of tools (up to top_k) + """ + # Early returns for cases where we can't/shouldn't filter + if not self.enabled: + return available_tools + + if not available_tools: + return available_tools + + if not query or not query.strip(): + return available_tools + + # Router should be built on startup - if not, something went wrong + if self.tool_router is None: + verbose_logger.warning("Router not initialized - was build_router_from_mcp_registry() called on startup?") + return available_tools + + # Run semantic filtering + try: + limit = top_k or self.top_k + matches = self.tool_router(text=query, limit=limit) + matched_tool_names = self._extract_tool_names_from_matches(matches) + + if not matched_tool_names: + return available_tools + + return self._get_tools_by_names(matched_tool_names, available_tools) + + except Exception as e: + verbose_logger.error(f"Semantic tool filter failed: {e}", exc_info=True) + return available_tools + + def _extract_tool_names_from_matches(self, matches) -> List[str]: + """Extract tool names from semantic router match results.""" + if not matches: + return [] + + # Handle single match + if hasattr(matches, "name") and matches.name: + return [matches.name] + + # Handle list of matches + if isinstance(matches, list): + return [m.name for m in matches if hasattr(m, "name") and m.name] + + return [] + + def _get_tools_by_names( + self, tool_names: List[str], available_tools: List[Any] + ) -> List[Any]: + """Get tools from available_tools by their names, preserving order.""" + # Match tools from available_tools (preserves format - dict or MCPTool) + matched_tools = [] + for tool in available_tools: + tool_name, _ = self._extract_tool_info(tool) + if tool_name in tool_names: + matched_tools.append(tool) + + # Reorder to match semantic router's ordering + tool_map = {self._extract_tool_info(t)[0]: t for t in matched_tools} + return [tool_map[name] for name in tool_names if name in tool_map] + + def extract_user_query(self, messages: List[Dict[str, Any]]) -> str: + """ + Extract user query from messages for /chat/completions or /responses. + + Args: + messages: List of message dictionaries (from 'messages' or 'input' field) + + Returns: + Extracted query string + """ + for msg in reversed(messages): + if msg.get("role") == "user": + content = msg.get("content", "") + + if isinstance(content, str): + return content + + if isinstance(content, list): + texts = [ + block.get("text", "") if isinstance(block, dict) else str(block) + for block in content + if isinstance(block, (dict, str)) + ] + return " ".join(texts) + + return "" diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py index 6d54c3871e5..890c4ae8fb2 100644 --- a/litellm/proxy/_experimental/mcp_server/server.py +++ b/litellm/proxy/_experimental/mcp_server/server.py @@ -5,12 +5,24 @@ import asyncio import contextlib -from datetime import datetime import traceback import uuid -from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Union, cast, Callable +from datetime import datetime +from typing import ( + Any, + AsyncIterator, + Callable, + Dict, + List, + Optional, + Tuple, + Union, + cast, +) + from fastapi import FastAPI, HTTPException from pydantic import AnyUrl, ConfigDict +from starlette.requests import Request as StarletteRequest from starlette.types import Receive, Scope, Send from litellm._logging import verbose_logger @@ -25,6 +37,7 @@ LITELLM_MCP_SERVER_VERSION, ) from litellm.proxy._types import UserAPIKeyAuth +from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.types.mcp import MCPAuth from litellm.types.mcp_server.mcp_server_manager import MCPInfo, MCPServer from litellm.types.utils import CallTypes, StandardLoggingMCPToolCall @@ -213,6 +226,7 @@ async def list_tools() -> List[MCPTool]: mcp_server_auth_headers, oauth2_headers, raw_headers, + _client_ip, ) = get_auth_context() verbose_logger.debug( f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}" @@ -276,6 +290,7 @@ async def mcp_server_tool_call( mcp_server_auth_headers, oauth2_headers, raw_headers, + _client_ip, ) = get_auth_context() verbose_logger.debug( @@ -288,7 +303,7 @@ async def mcp_server_tool_call( host_token = getattr(host_ctx.meta, 'progressToken', None) if host_token and hasattr(host_ctx, 'session') and host_ctx.session: host_session = host_ctx.session - + async def forward_progress(progress: float, total: float | None): """Forward progress notifications from external MCP to Host""" try: @@ -300,7 +315,7 @@ async def forward_progress(progress: float, total: float | None): verbose_logger.debug(f"Forwarded progress {progress}/{total} to Host") except Exception as e: verbose_logger.error(f"Failed to forward progress to Host: {e}") - + host_progress_callback = forward_progress verbose_logger.debug(f"Host progressToken captured: {host_token[:8]}...") except Exception as e: @@ -387,6 +402,7 @@ async def list_prompts() -> List[Prompt]: mcp_server_auth_headers, oauth2_headers, raw_headers, + _client_ip, ) = get_auth_context() verbose_logger.debug( f"MCP list_prompts - User API Key Auth from context: {user_api_key_auth}" @@ -440,6 +456,7 @@ async def get_prompt( mcp_server_auth_headers, oauth2_headers, raw_headers, + _client_ip, ) = get_auth_context() verbose_logger.debug( @@ -467,6 +484,7 @@ async def list_resources() -> List[Resource]: mcp_server_auth_headers, oauth2_headers, raw_headers, + _client_ip, ) = get_auth_context() verbose_logger.debug( f"MCP list_resources - User API Key Auth from context: {user_api_key_auth}" @@ -505,6 +523,7 @@ async def list_resource_templates() -> List[ResourceTemplate]: mcp_server_auth_headers, oauth2_headers, raw_headers, + _client_ip, ) = get_auth_context() verbose_logger.debug( f"MCP list_resource_templates - User API Key Auth from context: {user_api_key_auth}" @@ -544,6 +563,7 @@ async def read_resource(url: AnyUrl) -> list[ReadResourceContents]: mcp_server_auth_headers, oauth2_headers, raw_headers, + _client_ip, ) = get_auth_context() read_resource_result = await mcp_read_resource( @@ -702,13 +722,57 @@ def filter_tools_by_allowed_tools( return tools_to_return + def _get_client_ip_from_context() -> Optional[str]: + """ + Extract client_ip from auth context. + Returns None if context not set (caller should handle this as "no IP filtering"). + """ + try: + auth_user = auth_context_var.get() + if auth_user and isinstance(auth_user, MCPAuthenticatedUser): + return auth_user.client_ip + except Exception: + pass + return None + async def _get_allowed_mcp_servers( user_api_key_auth: Optional[UserAPIKeyAuth], mcp_servers: Optional[List[str]], + client_ip: Optional[str] = None, ) -> List[MCPServer]: - """Return allowed MCP servers for a request after applying filters.""" + """Return allowed MCP servers for a request after applying filters. + + Args: + user_api_key_auth: The authenticated user's API key info. + mcp_servers: Optional list of server names to filter to. + client_ip: Client IP for IP-based access control. If None, falls back to + auth context. Pass explicitly from request handlers for safety. + Note: If client_ip is None and auth context is not set, IP filtering is skipped. + This is intentional for internal callers but may indicate a bug if called + from a request handler without proper context setup. + """ + # Use explicit client_ip if provided, otherwise try auth context + if client_ip is None: + client_ip = _get_client_ip_from_context() + if client_ip is None: + verbose_logger.debug( + "MCP _get_allowed_mcp_servers called without client_ip and no auth context. " + "IP filtering will be skipped. This is expected for internal calls." + ) + allowed_mcp_server_ids = ( - await global_mcp_server_manager.get_allowed_mcp_servers(user_api_key_auth) + await global_mcp_server_manager.get_allowed_mcp_servers( + user_api_key_auth + ) + ) + allowed_mcp_server_ids = ( + global_mcp_server_manager.filter_server_ids_by_ip( + allowed_mcp_server_ids, client_ip + ) + ) + verbose_logger.debug( + "MCP IP filter: client_ip=%s, allowed_server_ids=%s", + client_ip, allowed_mcp_server_ids, ) allowed_mcp_servers: List[MCPServer] = [] for allowed_mcp_server_id in allowed_mcp_server_ids: @@ -1715,7 +1779,7 @@ async def _handle_managed_mcp_tool( oauth2_headers: Optional[Dict[str, str]] = None, raw_headers: Optional[Dict[str, str]] = None, litellm_logging_obj: Optional[Any] = None, - host_progress_callback: Optional[Callable] = None, + host_progress_callback: Optional[Callable] = None, ) -> CallToolResult: """Handle tool execution for managed server tools""" # Import here to avoid circular import @@ -1840,6 +1904,43 @@ async def extract_mcp_auth_context(scope, path): raw_headers, ) + def _strip_stale_mcp_session_header( + scope: Scope, + mgr: "StreamableHTTPSessionManager", + ) -> None: + """ + Strip stale ``mcp-session-id`` headers so the session manager + creates a fresh session instead of returning 404 "Session not found". + + When clients like VSCode reconnect after a reload they may resend a + session id that has already been cleaned up. Rather than letting the + SDK return a 404 error loop, we detect the stale id and remove the + header so a brand-new session is created transparently. + + Fixes https://github.com/BerriAI/litellm/issues/20292 + """ + _mcp_session_header = b"mcp-session-id" + _session_id: Optional[str] = None + for header_name, header_value in scope.get("headers", []): + if header_name == _mcp_session_header: + _session_id = header_value.decode("utf-8", errors="replace") + break + + if _session_id is None: + return + + known_sessions = getattr(mgr, "_server_instances", None) + if known_sessions is not None and _session_id not in known_sessions: + verbose_logger.warning( + "MCP session ID '%s' not found in active sessions. " + "Stripping stale header to force new session creation.", + _session_id, + ) + scope["headers"] = [ + (k, v) for k, v in scope["headers"] + if k != _mcp_session_header + ] + async def handle_streamable_http_mcp( scope: Scope, receive: Receive, send: Send ) -> None: @@ -1854,6 +1955,10 @@ async def handle_streamable_http_mcp( oauth2_headers, raw_headers, ) = await extract_mcp_auth_context(scope, path) + + # Extract client IP for MCP access control + _client_ip = IPAddressUtils.get_mcp_client_ip(StarletteRequest(scope)) + verbose_logger.debug( f"MCP request mcp_servers (header/path): {mcp_servers}" ) @@ -1862,11 +1967,11 @@ async def handle_streamable_http_mcp( ) # https://datatracker.ietf.org/doc/html/rfc9728#name-www-authenticate-response for server_name in mcp_servers or []: - server = global_mcp_server_manager.get_mcp_server_by_name(server_name) + server = global_mcp_server_manager.get_mcp_server_by_name( + server_name, client_ip=_client_ip + ) if server and server.auth_type == MCPAuth.oauth2 and not oauth2_headers: - from starlette.requests import Request - - request = Request(scope) + request = StarletteRequest(scope) base_url = str(request.base_url).rstrip("/") authorization_uri = ( @@ -1888,6 +1993,7 @@ async def handle_streamable_http_mcp( mcp_server_auth_headers=mcp_server_auth_headers, oauth2_headers=oauth2_headers, raw_headers=raw_headers, + client_ip=_client_ip, ) # Ensure session managers are initialized @@ -1896,13 +2002,16 @@ async def handle_streamable_http_mcp( # Give it a moment to start up await asyncio.sleep(0.1) + _strip_stale_mcp_session_header(scope, session_manager) + await session_manager.handle_request(scope, receive, send) + except HTTPException: + # Re-raise HTTP exceptions to preserve status codes and details + raise except Exception as e: - raise e verbose_logger.exception(f"Error handling MCP request: {e}") - # Instead of re-raising, try to send a graceful error response + # Try to send a graceful error response for non-HTTP exceptions try: - # Send a proper HTTP error response instead of letting the exception bubble up from starlette.responses import JSONResponse from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR @@ -1930,6 +2039,10 @@ async def handle_sse_mcp(scope: Scope, receive: Receive, send: Send) -> None: oauth2_headers, raw_headers, ) = await extract_mcp_auth_context(scope, path) + + # Extract client IP for MCP access control + _sse_client_ip = IPAddressUtils.get_mcp_client_ip(StarletteRequest(scope)) + verbose_logger.debug( f"MCP request mcp_servers (header/path): {mcp_servers}" ) @@ -1943,6 +2056,7 @@ async def handle_sse_mcp(scope: Scope, receive: Receive, send: Send) -> None: mcp_server_auth_headers=mcp_server_auth_headers, oauth2_headers=oauth2_headers, raw_headers=raw_headers, + client_ip=_sse_client_ip, ) if not _SESSION_MANAGERS_INITIALIZED: @@ -2006,6 +2120,7 @@ def set_auth_context( mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]] = None, oauth2_headers: Optional[Dict[str, str]] = None, raw_headers: Optional[Dict[str, str]] = None, + client_ip: Optional[str] = None, ) -> None: """ Set the UserAPIKeyAuth in the auth context variable. @@ -2015,6 +2130,7 @@ def set_auth_context( mcp_auth_header: MCP auth header to be passed to the MCP server (deprecated) mcp_servers: Optional list of server names and access groups to filter by mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value} + client_ip: Client IP address for MCP access control """ auth_user = MCPAuthenticatedUser( user_api_key_auth=user_api_key_auth, @@ -2023,6 +2139,7 @@ def set_auth_context( mcp_server_auth_headers=mcp_server_auth_headers, oauth2_headers=oauth2_headers, raw_headers=raw_headers, + client_ip=client_ip, ) auth_context_var.set(auth_user) @@ -2034,14 +2151,15 @@ def get_auth_context() -> ( Optional[Dict[str, Dict[str, str]]], Optional[Dict[str, str]], Optional[Dict[str, str]], + Optional[str], ] ): """ Get the UserAPIKeyAuth from the auth context variable. Returns: - Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[Dict[str, str]]]: - UserAPIKeyAuth object, MCP auth header (deprecated), MCP servers (can include access groups), and server-specific auth headers + Tuple containing: UserAPIKeyAuth, MCP auth header (deprecated), + MCP servers, server-specific auth headers, OAuth2 headers, raw headers, client IP """ auth_user = auth_context_var.get() if auth_user and isinstance(auth_user, MCPAuthenticatedUser): @@ -2052,8 +2170,9 @@ def get_auth_context() -> ( auth_user.mcp_server_auth_headers, auth_user.oauth2_headers, auth_user.raw_headers, + auth_user.client_ip, ) - return None, None, None, None, None, None + return None, None, None, None, None, None, None ######################################################## ############ End of Auth Context Functions ############# diff --git a/litellm/proxy/_experimental/out/404.html b/litellm/proxy/_experimental/out/404.html index a8bd30680ab..e40a85b4ddb 100644 --- a/litellm/proxy/_experimental/out/404.html +++ b/litellm/proxy/_experimental/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/litellm/proxy/_experimental/out/_next/static/chunks/1059-26bdac09bbb12a4b.js b/litellm/proxy/_experimental/out/_next/static/chunks/1059-26bdac09bbb12a4b.js deleted file mode 100644 index cd4f5e4e326..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/1059-26bdac09bbb12a4b.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1059],{83669:function(t,e,r){r.d(e,{Z:function(){return c}});var n=r(1119),o=r(2265),a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M699 353h-46.9c-10.2 0-19.9 4.9-25.9 13.3L469 584.3l-71.2-98.8c-6-8.3-15.6-13.3-25.9-13.3H325c-6.5 0-10.3 7.4-6.5 12.7l124.6 172.8a31.8 31.8 0 0051.7 0l210.6-292c3.9-5.3.1-12.7-6.4-12.7z"}},{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"}}]},name:"check-circle",theme:"outlined"},i=r(55015),c=o.forwardRef(function(t,e){return o.createElement(i.Z,(0,n.Z)({},t,{ref:e,icon:a}))})},62670:function(t,e,r){r.d(e,{Z:function(){return c}});var n=r(1119),o=r(2265),a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372zm47.7-395.2l-25.4-5.9V348.6c38 5.2 61.5 29 65.5 58.2.5 4 3.9 6.9 7.9 6.9h44.9c4.7 0 8.4-4.1 8-8.8-6.1-62.3-57.4-102.3-125.9-109.2V263c0-4.4-3.6-8-8-8h-28.1c-4.4 0-8 3.6-8 8v33c-70.8 6.9-126.2 46-126.2 119 0 67.6 49.8 100.2 102.1 112.7l24.7 6.3v142.7c-44.2-5.9-69-29.5-74.1-61.3-.6-3.8-4-6.6-7.9-6.6H363c-4.7 0-8.4 4-8 8.7 4.5 55 46.2 105.6 135.2 112.1V761c0 4.4 3.6 8 8 8h28.4c4.4 0 8-3.6 8-8.1l-.2-31.7c78.3-6.9 134.3-48.8 134.3-124-.1-69.4-44.2-100.4-109-116.4zm-68.6-16.2c-5.6-1.6-10.3-3.1-15-5-33.8-12.2-49.5-31.9-49.5-57.3 0-36.3 27.5-57 64.5-61.7v124zM534.3 677V543.3c3.1.9 5.9 1.6 8.8 2.2 47.3 14.4 63.2 34.4 63.2 65.1 0 39.1-29.4 62.6-72 66.4z"}}]},name:"dollar",theme:"outlined"},i=r(55015),c=o.forwardRef(function(t,e){return o.createElement(i.Z,(0,n.Z)({},t,{ref:e,icon:a}))})},45246:function(t,e,r){r.d(e,{Z:function(){return c}});var n=r(1119),o=r(2265),a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M696 480H328c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h368c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8z"}},{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"}}]},name:"minus-circle",theme:"outlined"},i=r(55015),c=o.forwardRef(function(t,e){return o.createElement(i.Z,(0,n.Z)({},t,{ref:e,icon:a}))})},89245:function(t,e,r){r.d(e,{Z:function(){return c}});var n=r(1119),o=r(2265),a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M909.1 209.3l-56.4 44.1C775.8 155.1 656.2 92 521.9 92 290 92 102.3 279.5 102 511.5 101.7 743.7 289.8 932 521.9 932c181.3 0 335.8-115 394.6-276.1 1.5-4.2-.7-8.9-4.9-10.3l-56.7-19.5a8 8 0 00-10.1 4.8c-1.8 5-3.8 10-5.9 14.9-17.3 41-42.1 77.8-73.7 109.4A344.77 344.77 0 01655.9 829c-42.3 17.9-87.4 27-133.8 27-46.5 0-91.5-9.1-133.8-27A341.5 341.5 0 01279 755.2a342.16 342.16 0 01-73.7-109.4c-17.9-42.4-27-87.4-27-133.9s9.1-91.5 27-133.9c17.3-41 42.1-77.8 73.7-109.4 31.6-31.6 68.4-56.4 109.3-73.8 42.3-17.9 87.4-27 133.8-27 46.5 0 91.5 9.1 133.8 27a341.5 341.5 0 01109.3 73.8c9.9 9.9 19.2 20.4 27.8 31.4l-60.2 47a8 8 0 003 14.1l175.6 43c5 1.2 9.9-2.6 9.9-7.7l.8-180.9c-.1-6.6-7.8-10.3-13-6.2z"}}]},name:"reload",theme:"outlined"},i=r(55015),c=o.forwardRef(function(t,e){return o.createElement(i.Z,(0,n.Z)({},t,{ref:e,icon:a}))})},77565:function(t,e,r){r.d(e,{Z:function(){return c}});var n=r(1119),o=r(2265),a={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"},i=r(55015),c=o.forwardRef(function(t,e){return o.createElement(i.Z,(0,n.Z)({},t,{ref:e,icon:a}))})},69993:function(t,e,r){r.d(e,{Z:function(){return c}});var n=r(1119),o=r(2265),a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M300 328a60 60 0 10120 0 60 60 0 10-120 0zM852 64H172c-17.7 0-32 14.3-32 32v660c0 17.7 14.3 32 32 32h680c17.7 0 32-14.3 32-32V96c0-17.7-14.3-32-32-32zm-32 660H204V128h616v596zM604 328a60 60 0 10120 0 60 60 0 10-120 0zm250.2 556H169.8c-16.5 0-29.8 14.3-29.8 32v36c0 4.4 3.3 8 7.4 8h729.1c4.1 0 7.4-3.6 7.4-8v-36c.1-17.7-13.2-32-29.7-32zM664 508H360c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h304c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"robot",theme:"outlined"},i=r(55015),c=o.forwardRef(function(t,e){return o.createElement(i.Z,(0,n.Z)({},t,{ref:e,icon:a}))})},58630:function(t,e,r){r.d(e,{Z:function(){return c}});var n=r(1119),o=r(2265),a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M876.6 239.5c-.5-.9-1.2-1.8-2-2.5-5-5-13.1-5-18.1 0L684.2 409.3l-67.9-67.9L788.7 169c.8-.8 1.4-1.6 2-2.5 3.6-6.1 1.6-13.9-4.5-17.5-98.2-58-226.8-44.7-311.3 39.7-67 67-89.2 162-66.5 247.4l-293 293c-3 3-2.8 7.9.3 11l169.7 169.7c3.1 3.1 8.1 3.3 11 .3l292.9-292.9c85.5 22.8 180.5.7 247.6-66.4 84.4-84.5 97.7-213.1 39.7-311.3zM786 499.8c-58.1 58.1-145.3 69.3-214.6 33.6l-8.8 8.8-.1-.1-274 274.1-79.2-79.2 230.1-230.1s0 .1.1.1l52.8-52.8c-35.7-69.3-24.5-156.5 33.6-214.6a184.2 184.2 0 01144-53.5L537 318.9a32.05 32.05 0 000 45.3l124.5 124.5a32.05 32.05 0 0045.3 0l132.8-132.8c3.7 51.8-14.4 104.8-53.6 143.9z"}}]},name:"tool",theme:"outlined"},i=r(55015),c=o.forwardRef(function(t,e){return o.createElement(i.Z,(0,n.Z)({},t,{ref:e,icon:a}))})},47323:function(t,e,r){r.d(e,{Z:function(){return b}});var n=r(5853),o=r(2265),a=r(47187),i=r(7084),c=r(13241),l=r(1153),s=r(26898);let d={xs:{paddingX:"px-1.5",paddingY:"py-1.5"},sm:{paddingX:"px-1.5",paddingY:"py-1.5"},md:{paddingX:"px-2",paddingY:"py-2"},lg:{paddingX:"px-2",paddingY:"py-2"},xl:{paddingX:"px-2.5",paddingY:"py-2.5"}},u={xs:{height:"h-3",width:"w-3"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-7",width:"w-7"},xl:{height:"h-9",width:"w-9"}},m={simple:{rounded:"",border:"",ring:"",shadow:""},light:{rounded:"rounded-tremor-default",border:"",ring:"",shadow:""},shadow:{rounded:"rounded-tremor-default",border:"border",ring:"",shadow:"shadow-tremor-card dark:shadow-dark-tremor-card"},solid:{rounded:"rounded-tremor-default",border:"border-2",ring:"ring-1",shadow:""},outlined:{rounded:"rounded-tremor-default",border:"border",ring:"ring-2",shadow:""}},g=(t,e)=>{switch(t){case"simple":return{textColor:e?(0,l.bM)(e,s.K.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:"",borderColor:"",ringColor:""};case"light":return{textColor:e?(0,l.bM)(e,s.K.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:e?(0,c.q)((0,l.bM)(e,s.K.background).bgColor,"bg-opacity-20"):"bg-tremor-brand-muted dark:bg-dark-tremor-brand-muted",borderColor:"",ringColor:""};case"shadow":return{textColor:e?(0,l.bM)(e,s.K.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:e?(0,c.q)((0,l.bM)(e,s.K.background).bgColor,"bg-opacity-20"):"bg-tremor-background dark:bg-dark-tremor-background",borderColor:"border-tremor-border dark:border-dark-tremor-border",ringColor:""};case"solid":return{textColor:e?(0,l.bM)(e,s.K.text).textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:e?(0,c.q)((0,l.bM)(e,s.K.background).bgColor,"bg-opacity-20"):"bg-tremor-brand dark:bg-dark-tremor-brand",borderColor:"border-tremor-brand-inverted dark:border-dark-tremor-brand-inverted",ringColor:"ring-tremor-ring dark:ring-dark-tremor-ring"};case"outlined":return{textColor:e?(0,l.bM)(e,s.K.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:e?(0,c.q)((0,l.bM)(e,s.K.background).bgColor,"bg-opacity-20"):"bg-tremor-background dark:bg-dark-tremor-background",borderColor:e?(0,l.bM)(e,s.K.ring).borderColor:"border-tremor-brand-subtle dark:border-dark-tremor-brand-subtle",ringColor:e?(0,c.q)((0,l.bM)(e,s.K.ring).ringColor,"ring-opacity-40"):"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"}}},p=(0,l.fn)("Icon"),b=o.forwardRef((t,e)=>{let{icon:r,variant:s="simple",tooltip:b,size:f=i.u8.SM,color:h,className:v}=t,y=(0,n._T)(t,["icon","variant","tooltip","size","color","className"]),w=g(s,h),{tooltipProps:x,getReferenceProps:k}=(0,a.l)();return o.createElement("span",Object.assign({ref:(0,l.lq)([e,x.refs.setReference]),className:(0,c.q)(p("root"),"inline-flex shrink-0 items-center justify-center",w.bgColor,w.textColor,w.borderColor,w.ringColor,m[s].rounded,m[s].border,m[s].shadow,m[s].ring,d[f].paddingX,d[f].paddingY,v)},k,y),o.createElement(a.Z,Object.assign({text:b},x)),o.createElement(r,{className:(0,c.q)(p("icon"),"shrink-0",u[f].height,u[f].width)}))});b.displayName="Icon"},67101:function(t,e,r){r.d(e,{Z:function(){return d}});var n=r(5853),o=r(13241),a=r(1153),i=r(2265),c=r(9496);let l=(0,a.fn)("Grid"),s=(t,e)=>t&&Object.keys(e).includes(String(t))?e[t]:"",d=i.forwardRef((t,e)=>{let{numItems:r=1,numItemsSm:a,numItemsMd:d,numItemsLg:u,children:m,className:g}=t,p=(0,n._T)(t,["numItems","numItemsSm","numItemsMd","numItemsLg","children","className"]),b=s(r,c._m),f=s(a,c.LH),h=s(d,c.l5),v=s(u,c.N4),y=(0,o.q)(b,f,h,v);return i.createElement("div",Object.assign({ref:e,className:(0,o.q)(l("root"),"grid",y,g)},p),m)});d.displayName="Grid"},9496:function(t,e,r){r.d(e,{LH:function(){return o},N4:function(){return i},PT:function(){return c},SP:function(){return l},VS:function(){return s},_m:function(){return n},_w:function(){return d},l5:function(){return a}});let n={0:"grid-cols-none",1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6",7:"grid-cols-7",8:"grid-cols-8",9:"grid-cols-9",10:"grid-cols-10",11:"grid-cols-11",12:"grid-cols-12"},o={0:"sm:grid-cols-none",1:"sm:grid-cols-1",2:"sm:grid-cols-2",3:"sm:grid-cols-3",4:"sm:grid-cols-4",5:"sm:grid-cols-5",6:"sm:grid-cols-6",7:"sm:grid-cols-7",8:"sm:grid-cols-8",9:"sm:grid-cols-9",10:"sm:grid-cols-10",11:"sm:grid-cols-11",12:"sm:grid-cols-12"},a={0:"md:grid-cols-none",1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4",5:"md:grid-cols-5",6:"md:grid-cols-6",7:"md:grid-cols-7",8:"md:grid-cols-8",9:"md:grid-cols-9",10:"md:grid-cols-10",11:"md:grid-cols-11",12:"md:grid-cols-12"},i={0:"lg:grid-cols-none",1:"lg:grid-cols-1",2:"lg:grid-cols-2",3:"lg:grid-cols-3",4:"lg:grid-cols-4",5:"lg:grid-cols-5",6:"lg:grid-cols-6",7:"lg:grid-cols-7",8:"lg:grid-cols-8",9:"lg:grid-cols-9",10:"lg:grid-cols-10",11:"lg:grid-cols-11",12:"lg:grid-cols-12"},c={1:"col-span-1",2:"col-span-2",3:"col-span-3",4:"col-span-4",5:"col-span-5",6:"col-span-6",7:"col-span-7",8:"col-span-8",9:"col-span-9",10:"col-span-10",11:"col-span-11",12:"col-span-12",13:"col-span-13"},l={1:"sm:col-span-1",2:"sm:col-span-2",3:"sm:col-span-3",4:"sm:col-span-4",5:"sm:col-span-5",6:"sm:col-span-6",7:"sm:col-span-7",8:"sm:col-span-8",9:"sm:col-span-9",10:"sm:col-span-10",11:"sm:col-span-11",12:"sm:col-span-12",13:"sm:col-span-13"},s={1:"md:col-span-1",2:"md:col-span-2",3:"md:col-span-3",4:"md:col-span-4",5:"md:col-span-5",6:"md:col-span-6",7:"md:col-span-7",8:"md:col-span-8",9:"md:col-span-9",10:"md:col-span-10",11:"md:col-span-11",12:"md:col-span-12",13:"md:col-span-13"},d={1:"lg:col-span-1",2:"lg:col-span-2",3:"lg:col-span-3",4:"lg:col-span-4",5:"lg:col-span-5",6:"lg:col-span-6",7:"lg:col-span-7",8:"lg:col-span-8",9:"lg:col-span-9",10:"lg:col-span-10",11:"lg:col-span-11",12:"lg:col-span-12",13:"lg:col-span-13"}},96761:function(t,e,r){r.d(e,{Z:function(){return l}});var n=r(5853),o=r(26898),a=r(13241),i=r(1153),c=r(2265);let l=c.forwardRef((t,e)=>{let{color:r,children:l,className:s}=t,d=(0,n._T)(t,["color","children","className"]);return c.createElement("p",Object.assign({ref:e,className:(0,a.q)("font-medium text-tremor-title",r?(0,i.bM)(r,o.K.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",s)},d),l)});l.displayName="Title"},33866:function(t,e,r){r.d(e,{Z:function(){return I}});var n=r(2265),o=r(36760),a=r.n(o),i=r(66632),c=r(93350),l=r(19722),s=r(71744),d=r(93463),u=r(12918),m=r(18536),g=r(71140),p=r(99320);let b=new d.E4("antStatusProcessing",{"0%":{transform:"scale(0.8)",opacity:.5},"100%":{transform:"scale(2.4)",opacity:0}}),f=new d.E4("antZoomBadgeIn",{"0%":{transform:"scale(0) translate(50%, -50%)",opacity:0},"100%":{transform:"scale(1) translate(50%, -50%)"}}),h=new d.E4("antZoomBadgeOut",{"0%":{transform:"scale(1) translate(50%, -50%)"},"100%":{transform:"scale(0) translate(50%, -50%)",opacity:0}}),v=new d.E4("antNoWrapperZoomBadgeIn",{"0%":{transform:"scale(0)",opacity:0},"100%":{transform:"scale(1)"}}),y=new d.E4("antNoWrapperZoomBadgeOut",{"0%":{transform:"scale(1)"},"100%":{transform:"scale(0)",opacity:0}}),w=new d.E4("antBadgeLoadingCircle",{"0%":{transformOrigin:"50%"},"100%":{transform:"translate(50%, -50%) rotate(360deg)",transformOrigin:"50%"}}),x=t=>{let{componentCls:e,iconCls:r,antCls:n,badgeShadowSize:o,textFontSize:a,textFontSizeSM:i,statusSize:c,dotSize:l,textFontWeight:s,indicatorHeight:g,indicatorHeightSM:p,marginXS:x,calc:k}=t,O="".concat(n,"-scroll-number"),C=(0,m.Z)(t,(t,r)=>{let{darkColor:n}=r;return{["&".concat(e," ").concat(e,"-color-").concat(t)]:{background:n,["&:not(".concat(e,"-count)")]:{color:n},"a:hover &":{background:n}}}});return{[e]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,u.Wf)(t)),{position:"relative",display:"inline-block",width:"fit-content",lineHeight:1,["".concat(e,"-count")]:{display:"inline-flex",justifyContent:"center",zIndex:t.indicatorZIndex,minWidth:g,height:g,color:t.badgeTextColor,fontWeight:s,fontSize:a,lineHeight:(0,d.bf)(g),whiteSpace:"nowrap",textAlign:"center",background:t.badgeColor,borderRadius:k(g).div(2).equal(),boxShadow:"0 0 0 ".concat((0,d.bf)(o)," ").concat(t.badgeShadowColor),transition:"background ".concat(t.motionDurationMid),a:{color:t.badgeTextColor},"a:hover":{color:t.badgeTextColor},"a:hover &":{background:t.badgeColorHover}},["".concat(e,"-count-sm")]:{minWidth:p,height:p,fontSize:i,lineHeight:(0,d.bf)(p),borderRadius:k(p).div(2).equal()},["".concat(e,"-multiple-words")]:{padding:"0 ".concat((0,d.bf)(t.paddingXS)),bdi:{unicodeBidi:"plaintext"}},["".concat(e,"-dot")]:{zIndex:t.indicatorZIndex,width:l,minWidth:l,height:l,background:t.badgeColor,borderRadius:"100%",boxShadow:"0 0 0 ".concat((0,d.bf)(o)," ").concat(t.badgeShadowColor)},["".concat(e,"-count, ").concat(e,"-dot, ").concat(O,"-custom-component")]:{position:"absolute",top:0,insetInlineEnd:0,transform:"translate(50%, -50%)",transformOrigin:"100% 0%",["&".concat(r,"-spin")]:{animationName:w,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear"}},["&".concat(e,"-status")]:{lineHeight:"inherit",verticalAlign:"baseline",["".concat(e,"-status-dot")]:{position:"relative",top:-1,display:"inline-block",width:c,height:c,verticalAlign:"middle",borderRadius:"50%"},["".concat(e,"-status-success")]:{backgroundColor:t.colorSuccess},["".concat(e,"-status-processing")]:{overflow:"visible",color:t.colorInfo,backgroundColor:t.colorInfo,borderColor:"currentcolor","&::after":{position:"absolute",top:0,insetInlineStart:0,width:"100%",height:"100%",borderWidth:o,borderStyle:"solid",borderColor:"inherit",borderRadius:"50%",animationName:b,animationDuration:t.badgeProcessingDuration,animationIterationCount:"infinite",animationTimingFunction:"ease-in-out",content:'""'}},["".concat(e,"-status-default")]:{backgroundColor:t.colorTextPlaceholder},["".concat(e,"-status-error")]:{backgroundColor:t.colorError},["".concat(e,"-status-warning")]:{backgroundColor:t.colorWarning},["".concat(e,"-status-text")]:{marginInlineStart:x,color:t.colorText,fontSize:t.fontSize}}}),C),{["".concat(e,"-zoom-appear, ").concat(e,"-zoom-enter")]:{animationName:f,animationDuration:t.motionDurationSlow,animationTimingFunction:t.motionEaseOutBack,animationFillMode:"both"},["".concat(e,"-zoom-leave")]:{animationName:h,animationDuration:t.motionDurationSlow,animationTimingFunction:t.motionEaseOutBack,animationFillMode:"both"},["&".concat(e,"-not-a-wrapper")]:{["".concat(e,"-zoom-appear, ").concat(e,"-zoom-enter")]:{animationName:v,animationDuration:t.motionDurationSlow,animationTimingFunction:t.motionEaseOutBack},["".concat(e,"-zoom-leave")]:{animationName:y,animationDuration:t.motionDurationSlow,animationTimingFunction:t.motionEaseOutBack},["&:not(".concat(e,"-status)")]:{verticalAlign:"middle"},["".concat(O,"-custom-component, ").concat(e,"-count")]:{transform:"none"},["".concat(O,"-custom-component, ").concat(O)]:{position:"relative",top:"auto",display:"block",transformOrigin:"50% 50%"}},[O]:{overflow:"hidden",transition:"all ".concat(t.motionDurationMid," ").concat(t.motionEaseOutBack),["".concat(O,"-only")]:{position:"relative",display:"inline-block",height:g,transition:"all ".concat(t.motionDurationSlow," ").concat(t.motionEaseOutBack),WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden",["> p".concat(O,"-only-unit")]:{height:g,margin:0,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden"}},["".concat(O,"-symbol")]:{verticalAlign:"top"}},"&-rtl":{direction:"rtl",["".concat(e,"-count, ").concat(e,"-dot, ").concat(O,"-custom-component")]:{transform:"translate(-50%, -50%)"}}})}},k=t=>{let{fontHeight:e,lineWidth:r,marginXS:n,colorBorderBg:o}=t,a=t.colorTextLightSolid,i=t.colorError,c=t.colorErrorHover;return(0,g.IX)(t,{badgeFontHeight:e,badgeShadowSize:r,badgeTextColor:a,badgeColor:i,badgeColorHover:c,badgeShadowColor:o,badgeProcessingDuration:"1.2s",badgeRibbonOffset:n,badgeRibbonCornerTransform:"scaleY(0.75)",badgeRibbonCornerFilter:"brightness(75%)"})},O=t=>{let{fontSize:e,lineHeight:r,fontSizeSM:n,lineWidth:o}=t;return{indicatorZIndex:"auto",indicatorHeight:Math.round(e*r)-2*o,indicatorHeightSM:e,dotSize:n/2,textFontSize:n,textFontSizeSM:n,textFontWeight:"normal",statusSize:n/2}};var C=(0,p.I$)("Badge",t=>x(k(t)),O);let E=t=>{let{antCls:e,badgeFontHeight:r,marginXS:n,badgeRibbonOffset:o,calc:a}=t,i="".concat(e,"-ribbon"),c=(0,m.Z)(t,(t,e)=>{let{darkColor:r}=e;return{["&".concat(i,"-color-").concat(t)]:{background:r,color:r}}});return{["".concat(e,"-ribbon-wrapper")]:{position:"relative"},[i]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,u.Wf)(t)),{position:"absolute",top:n,padding:"0 ".concat((0,d.bf)(t.paddingXS)),color:t.colorPrimary,lineHeight:(0,d.bf)(r),whiteSpace:"nowrap",backgroundColor:t.colorPrimary,borderRadius:t.borderRadiusSM,["".concat(i,"-text")]:{color:t.badgeTextColor},["".concat(i,"-corner")]:{position:"absolute",top:"100%",width:o,height:o,color:"currentcolor",border:"".concat((0,d.bf)(a(o).div(2).equal())," solid"),transform:t.badgeRibbonCornerTransform,transformOrigin:"top",filter:t.badgeRibbonCornerFilter}}),c),{["&".concat(i,"-placement-end")]:{insetInlineEnd:a(o).mul(-1).equal(),borderEndEndRadius:0,["".concat(i,"-corner")]:{insetInlineEnd:0,borderInlineEndColor:"transparent",borderBlockEndColor:"transparent"}},["&".concat(i,"-placement-start")]:{insetInlineStart:a(o).mul(-1).equal(),borderEndStartRadius:0,["".concat(i,"-corner")]:{insetInlineStart:0,borderBlockEndColor:"transparent",borderInlineStartColor:"transparent"}},"&-rtl":{direction:"rtl"}})}};var S=(0,p.I$)(["Badge","Ribbon"],t=>E(k(t)),O);let N=t=>{let e;let{prefixCls:r,value:o,current:i,offset:c=0}=t;return c&&(e={position:"absolute",top:"".concat(c,"00%"),left:0}),n.createElement("span",{style:e,className:a()("".concat(r,"-only-unit"),{current:i})},o)};var j=t=>{let e,r;let{prefixCls:o,count:a,value:i}=t,c=Number(i),l=Math.abs(a),[s,d]=n.useState(c),[u,m]=n.useState(l),g=()=>{d(c),m(l)};if(n.useEffect(()=>{let t=setTimeout(g,1e3);return()=>clearTimeout(t)},[c]),s===c||Number.isNaN(c)||Number.isNaN(s))e=[n.createElement(N,Object.assign({},t,{key:c,current:!0}))],r={transition:"none"};else{e=[];let o=c+10,a=[];for(let t=c;t<=o;t+=1)a.push(t);let i=ut%10===s);e=(i<0?a.slice(0,d+1):a.slice(d)).map((e,r)=>n.createElement(N,Object.assign({},t,{key:e,value:e%10,offset:i<0?r-d:r,current:r===d}))),r={transform:"translateY(".concat(-function(t,e,r){let n=t,o=0;for(;(n+10)%10!==e;)n+=r,o+=r;return o}(s,c,i),"00%)")}}return n.createElement("span",{className:"".concat(o,"-only"),style:r,onTransitionEnd:g},e)},M=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&0>e.indexOf(n)&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,n=Object.getOwnPropertySymbols(t);oe.indexOf(n[o])&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]]);return r};let z=n.forwardRef((t,e)=>{let{prefixCls:r,count:o,className:i,motionClassName:c,style:d,title:u,show:m,component:g="sup",children:p}=t,b=M(t,["prefixCls","count","className","motionClassName","style","title","show","component","children"]),{getPrefixCls:f}=n.useContext(s.E_),h=f("scroll-number",r),v=Object.assign(Object.assign({},b),{"data-show":m,style:d,className:a()(h,i,c),title:u}),y=o;if(o&&Number(o)%1==0){let t=String(o).split("");y=n.createElement("bdi",null,t.map((e,r)=>n.createElement(j,{prefixCls:h,count:Number(o),value:e,key:t.length-r})))}return((null==d?void 0:d.borderColor)&&(v.style=Object.assign(Object.assign({},d),{boxShadow:"0 0 0 1px ".concat(d.borderColor," inset")})),p)?(0,l.Tm)(p,t=>({className:a()("".concat(h,"-custom-component"),null==t?void 0:t.className,c)})):n.createElement(g,Object.assign({},v,{ref:e}),y)});var Z=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&0>e.indexOf(n)&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,n=Object.getOwnPropertySymbols(t);oe.indexOf(n[o])&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]]);return r};let R=n.forwardRef((t,e)=>{var r,o,d,u,m;let{prefixCls:g,scrollNumberPrefixCls:p,children:b,status:f,text:h,color:v,count:y=null,overflowCount:w=99,dot:x=!1,size:k="default",title:O,offset:E,style:S,className:N,rootClassName:j,classNames:M,styles:R,showZero:I=!1}=t,L=Z(t,["prefixCls","scrollNumberPrefixCls","children","status","text","color","count","overflowCount","dot","size","title","offset","style","className","rootClassName","classNames","styles","showZero"]),{getPrefixCls:B,direction:T,badge:P}=n.useContext(s.E_),W=B("badge",g),[A,q,H]=C(W),G=y>w?"".concat(w,"+"):y,D="0"===G||0===G||"0"===h||0===h,K=null===y||D&&!I,V=(null!=f||null!=v)&&K,F=null!=f||!D,_=x&&!D,X=_?"":G,Y=(0,n.useMemo)(()=>((null==X||""===X)&&(null==h||""===h)||D&&!I)&&!_,[X,D,I,_,h]),$=(0,n.useRef)(y);Y||($.current=y);let U=$.current,J=(0,n.useRef)(X);Y||(J.current=X);let Q=J.current,tt=(0,n.useRef)(_);Y||(tt.current=_);let te=(0,n.useMemo)(()=>{if(!E)return Object.assign(Object.assign({},null==P?void 0:P.style),S);let t={marginTop:E[1]};return"rtl"===T?t.left=Number.parseInt(E[0],10):t.right=-Number.parseInt(E[0],10),Object.assign(Object.assign(Object.assign({},t),null==P?void 0:P.style),S)},[T,E,S,null==P?void 0:P.style]),tr=null!=O?O:"string"==typeof U||"number"==typeof U?U:void 0,tn=!Y&&(0===h?I:!!h&&!0!==h),to=tn?n.createElement("span",{className:"".concat(W,"-status-text")},h):null,ta=U&&"object"==typeof U?(0,l.Tm)(U,t=>({style:Object.assign(Object.assign({},te),t.style)})):void 0,ti=(0,c.o2)(v,!1),tc=a()(null==M?void 0:M.indicator,null===(r=null==P?void 0:P.classNames)||void 0===r?void 0:r.indicator,{["".concat(W,"-status-dot")]:V,["".concat(W,"-status-").concat(f)]:!!f,["".concat(W,"-color-").concat(v)]:ti}),tl={};v&&!ti&&(tl.color=v,tl.background=v);let ts=a()(W,{["".concat(W,"-status")]:V,["".concat(W,"-not-a-wrapper")]:!b,["".concat(W,"-rtl")]:"rtl"===T},N,j,null==P?void 0:P.className,null===(o=null==P?void 0:P.classNames)||void 0===o?void 0:o.root,null==M?void 0:M.root,q,H);if(!b&&V&&(h||F||!K)){let t=te.color;return A(n.createElement("span",Object.assign({},L,{className:ts,style:Object.assign(Object.assign(Object.assign({},null==R?void 0:R.root),null===(d=null==P?void 0:P.styles)||void 0===d?void 0:d.root),te)}),n.createElement("span",{className:tc,style:Object.assign(Object.assign(Object.assign({},null==R?void 0:R.indicator),null===(u=null==P?void 0:P.styles)||void 0===u?void 0:u.indicator),tl)}),tn&&n.createElement("span",{style:{color:t},className:"".concat(W,"-status-text")},h)))}return A(n.createElement("span",Object.assign({ref:e},L,{className:ts,style:Object.assign(Object.assign({},null===(m=null==P?void 0:P.styles)||void 0===m?void 0:m.root),null==R?void 0:R.root)}),b,n.createElement(i.ZP,{visible:!Y,motionName:"".concat(W,"-zoom"),motionAppear:!1,motionDeadline:1e3},t=>{var e,r;let{className:o}=t,i=B("scroll-number",p),c=tt.current,l=a()(null==M?void 0:M.indicator,null===(e=null==P?void 0:P.classNames)||void 0===e?void 0:e.indicator,{["".concat(W,"-dot")]:c,["".concat(W,"-count")]:!c,["".concat(W,"-count-sm")]:"small"===k,["".concat(W,"-multiple-words")]:!c&&Q&&Q.toString().length>1,["".concat(W,"-status-").concat(f)]:!!f,["".concat(W,"-color-").concat(v)]:ti}),s=Object.assign(Object.assign(Object.assign({},null==R?void 0:R.indicator),null===(r=null==P?void 0:P.styles)||void 0===r?void 0:r.indicator),te);return v&&!ti&&((s=s||{}).background=v),n.createElement(z,{prefixCls:i,show:!Y,motionClassName:o,className:l,count:Q,title:tr,style:s,key:"scrollNumber"},ta)}),to))});R.Ribbon=t=>{let{className:e,prefixCls:r,style:o,color:i,children:l,text:d,placement:u="end",rootClassName:m}=t,{getPrefixCls:g,direction:p}=n.useContext(s.E_),b=g("ribbon",r),f="".concat(b,"-wrapper"),[h,v,y]=S(b,f),w=(0,c.o2)(i,!1),x=a()(b,"".concat(b,"-placement-").concat(u),{["".concat(b,"-rtl")]:"rtl"===p,["".concat(b,"-color-").concat(i)]:w},e),k={},O={};return i&&!w&&(k.background=i,O.color=i),h(n.createElement("div",{className:a()(f,m,v,y)},l,n.createElement("div",{className:a()(x,v),style:Object.assign(Object.assign({},k),o)},n.createElement("span",{className:"".concat(b,"-text")},d),n.createElement("div",{className:"".concat(b,"-corner"),style:O}))))};var I=R},58760:function(t,e,r){r.d(e,{Z:function(){return S}});var n=r(2265),o=r(36760),a=r.n(o),i=r(45287);function c(t){return["small","middle","large"].includes(t)}function l(t){return!!t&&"number"==typeof t&&!Number.isNaN(t)}var s=r(71744),d=r(77685),u=r(17691),m=r(99320);let g=t=>{let{componentCls:e,borderRadius:r,paddingSM:n,colorBorder:o,paddingXS:a,fontSizeLG:i,fontSizeSM:c,borderRadiusLG:l,borderRadiusSM:s,colorBgContainerDisabled:d,lineWidth:m}=t;return{[e]:[{display:"inline-flex",alignItems:"center",gap:0,paddingInline:n,margin:0,background:d,borderWidth:m,borderStyle:"solid",borderColor:o,borderRadius:r,"&-large":{fontSize:i,borderRadius:l},"&-small":{paddingInline:a,borderRadius:s,fontSize:c},"&-compact-last-item":{borderEndStartRadius:0,borderStartStartRadius:0},"&-compact-first-item":{borderEndEndRadius:0,borderStartEndRadius:0},"&-compact-item:not(:first-child):not(:last-child)":{borderRadius:0},"&-compact-item:not(:last-child)":{borderInlineEndWidth:0}},(0,u.c)(t,{focus:!1})]}};var p=(0,m.I$)(["Space","Addon"],t=>[g(t)]),b=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&0>e.indexOf(n)&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,n=Object.getOwnPropertySymbols(t);oe.indexOf(n[o])&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]]);return r};let f=n.forwardRef((t,e)=>{let{className:r,children:o,style:i,prefixCls:c}=t,l=b(t,["className","children","style","prefixCls"]),{getPrefixCls:u,direction:m}=n.useContext(s.E_),g=u("space-addon",c),[f,h,v]=p(g),{compactItemClassnames:y,compactSize:w}=(0,d.ri)(g,m),x=a()(g,h,y,v,{["".concat(g,"-").concat(w)]:w},r);return f(n.createElement("div",Object.assign({ref:e,className:x,style:i},l),o))}),h=n.createContext({latestIndex:0}),v=h.Provider;var y=t=>{let{className:e,index:r,children:o,split:a,style:i}=t,{latestIndex:c}=n.useContext(h);return null==o?null:n.createElement(n.Fragment,null,n.createElement("div",{className:e,style:i},o),r{let{componentCls:e,antCls:r}=t;return{[e]:{display:"inline-flex","&-rtl":{direction:"rtl"},"&-vertical":{flexDirection:"column"},"&-align":{flexDirection:"column","&-center":{alignItems:"center"},"&-start":{alignItems:"flex-start"},"&-end":{alignItems:"flex-end"},"&-baseline":{alignItems:"baseline"}},["".concat(e,"-item:empty")]:{display:"none"},["".concat(e,"-item > ").concat(r,"-badge-not-a-wrapper:only-child")]:{display:"block"}}}},k=t=>{let{componentCls:e}=t;return{[e]:{"&-gap-row-small":{rowGap:t.spaceGapSmallSize},"&-gap-row-middle":{rowGap:t.spaceGapMiddleSize},"&-gap-row-large":{rowGap:t.spaceGapLargeSize},"&-gap-col-small":{columnGap:t.spaceGapSmallSize},"&-gap-col-middle":{columnGap:t.spaceGapMiddleSize},"&-gap-col-large":{columnGap:t.spaceGapLargeSize}}}};var O=(0,m.I$)("Space",t=>{let e=(0,w.IX)(t,{spaceGapSmallSize:t.paddingXS,spaceGapMiddleSize:t.padding,spaceGapLargeSize:t.paddingLG});return[x(e),k(e)]},()=>({}),{resetStyle:!1}),C=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&0>e.indexOf(n)&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,n=Object.getOwnPropertySymbols(t);oe.indexOf(n[o])&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]]);return r};let E=n.forwardRef((t,e)=>{var r;let{getPrefixCls:o,direction:d,size:u,className:m,style:g,classNames:p,styles:b}=(0,s.dj)("space"),{size:f=null!=u?u:"small",align:h,className:w,rootClassName:x,children:k,direction:E="horizontal",prefixCls:S,split:N,style:j,wrap:M=!1,classNames:z,styles:Z}=t,R=C(t,["size","align","className","rootClassName","children","direction","prefixCls","split","style","wrap","classNames","styles"]),[I,L]=Array.isArray(f)?f:[f,f],B=c(L),T=c(I),P=l(L),W=l(I),A=(0,i.Z)(k,{keepEmpty:!0}),q=void 0===h&&"horizontal"===E?"center":h,H=o("space",S),[G,D,K]=O(H),V=a()(H,m,D,"".concat(H,"-").concat(E),{["".concat(H,"-rtl")]:"rtl"===d,["".concat(H,"-align-").concat(q)]:q,["".concat(H,"-gap-row-").concat(L)]:B,["".concat(H,"-gap-col-").concat(I)]:T},w,x,K),F=a()("".concat(H,"-item"),null!==(r=null==z?void 0:z.item)&&void 0!==r?r:p.item),_=Object.assign(Object.assign({},b.item),null==Z?void 0:Z.item),X=A.map((t,e)=>{let r=(null==t?void 0:t.key)||"".concat(F,"-").concat(e);return n.createElement(y,{className:F,key:r,index:e,split:N,style:_},t)}),Y=n.useMemo(()=>({latestIndex:A.reduce((t,e,r)=>null!=e?r:t,0)}),[A]);if(0===A.length)return null;let $={};return M&&($.flexWrap="wrap"),!T&&W&&($.columnGap=I),!B&&P&&($.rowGap=L),G(n.createElement("div",Object.assign({ref:e,className:V,style:Object.assign(Object.assign(Object.assign({},$),g),j)},R),n.createElement(v,{value:Y},X)))});E.Compact=d.ZP,E.Addon=f;var S=E},79205:function(t,e,r){r.d(e,{Z:function(){return u}});var n=r(2265);let o=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),a=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,e,r)=>r?r.toUpperCase():e.toLowerCase()),i=t=>{let e=a(t);return e.charAt(0).toUpperCase()+e.slice(1)},c=function(){for(var t=arguments.length,e=Array(t),r=0;r!!t&&""!==t.trim()&&r.indexOf(t)===e).join(" ").trim()},l=t=>{for(let e in t)if(e.startsWith("aria-")||"role"===e||"title"===e)return!0};var s={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};let d=(0,n.forwardRef)((t,e)=>{let{color:r="currentColor",size:o=24,strokeWidth:a=2,absoluteStrokeWidth:i,className:d="",children:u,iconNode:m,...g}=t;return(0,n.createElement)("svg",{ref:e,...s,width:o,height:o,stroke:r,strokeWidth:i?24*Number(a)/Number(o):a,className:c("lucide",d),...!u&&!l(g)&&{"aria-hidden":"true"},...g},[...m.map(t=>{let[e,r]=t;return(0,n.createElement)(e,r)}),...Array.isArray(u)?u:[u]])}),u=(t,e)=>{let r=(0,n.forwardRef)((r,a)=>{let{className:l,...s}=r;return(0,n.createElement)(d,{ref:a,iconNode:e,className:c("lucide-".concat(o(i(t))),"lucide-".concat(t),l),...s})});return r.displayName=i(t),r}},30401:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]])},64935:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("code",[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]])},78867:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]])},96362:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("external-link",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]])},29202:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]])},54001:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]])},96137:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]])},80221:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("terminal",[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]])},11239:function(t,e,r){r.d(e,{Z:function(){return n}});let n=(0,r(79205).Z)("zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]])},10900:function(t,e,r){var n=r(2265);let o=n.forwardRef(function(t,e){return n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor","aria-hidden":"true",ref:e},t),n.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 19l-7-7m0 0l7-7m-7 7h18"}))});e.Z=o},71437:function(t,e,r){var n=r(2265);let o=n.forwardRef(function(t,e){return n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor","aria-hidden":"true",ref:e},t),n.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),n.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"}))});e.Z=o},82376:function(t,e,r){var n=r(2265);let o=n.forwardRef(function(t,e){return n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor","aria-hidden":"true",ref:e},t),n.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"}))});e.Z=o},53410:function(t,e,r){var n=r(2265);let o=n.forwardRef(function(t,e){return n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor","aria-hidden":"true",ref:e},t),n.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"}))});e.Z=o},74998:function(t,e,r){var n=r(2265);let o=n.forwardRef(function(t,e){return n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor","aria-hidden":"true",ref:e},t),n.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"}))});e.Z=o},21770:function(t,e,r){r.d(e,{D:function(){return d}});var n=r(2265),o=r(2894),a=r(18238),i=r(24112),c=r(45345),l=class extends i.l{#t;#e=void 0;#r;#n;constructor(t,e){super(),this.#t=t,this.setOptions(e),this.bindMethods(),this.#o()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let e=this.options;this.options=this.#t.defaultMutationOptions(t),(0,c.VS)(this.options,e)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),e?.mutationKey&&this.options.mutationKey&&(0,c.Ym)(e.mutationKey)!==(0,c.Ym)(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(t){this.#o(),this.#a(t)}getCurrentResult(){return this.#e}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#o(),this.#a()}mutate(t,e){return this.#n=e,this.#r?.removeObserver(this),this.#r=this.#t.getMutationCache().build(this.#t,this.options),this.#r.addObserver(this),this.#r.execute(t)}#o(){let t=this.#r?.state??(0,o.R)();this.#e={...t,isPending:"pending"===t.status,isSuccess:"success"===t.status,isError:"error"===t.status,isIdle:"idle"===t.status,mutate:this.mutate,reset:this.reset}}#a(t){a.Vr.batch(()=>{if(this.#n&&this.hasListeners()){let e=this.#e.variables,r=this.#e.context,n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};t?.type==="success"?(this.#n.onSuccess?.(t.data,e,r,n),this.#n.onSettled?.(t.data,null,e,r,n)):t?.type==="error"&&(this.#n.onError?.(t.error,e,r,n),this.#n.onSettled?.(void 0,t.error,e,r,n))}this.listeners.forEach(t=>{t(this.#e)})})}},s=r(29827);function d(t,e){let r=(0,s.NL)(e),[o]=n.useState(()=>new l(r,t));n.useEffect(()=>{o.setOptions(t)},[o,t]);let i=n.useSyncExternalStore(n.useCallback(t=>o.subscribe(a.Vr.batchCalls(t)),[o]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),d=n.useCallback((t,e)=>{o.mutate(t,e).catch(c.ZT)},[o]);if(i.error&&(0,c.L3)(o.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:d,mutateAsync:i.mutate}}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1098-a1702da59647cf14.js b/litellm/proxy/_experimental/out/_next/static/chunks/1098-a1702da59647cf14.js deleted file mode 100644 index 8bdb738f169..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/1098-a1702da59647cf14.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1098],{30280:function(e,t,l){l.d(t,{EX:function(){return c},Km:function(){return o},Tv:function(){return u}});var s=l(11713),a=l(45345),r=l(90246),i=l(19250),n=l(39760);let o=(0,r.n)("keys"),d=async function(e,t,l){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};try{let a=(0,i.getProxyBaseUrl)(),r=new URLSearchParams(Object.entries({team_id:s.teamID,organization_id:s.organizationID,key_alias:s.selectedKeyAlias,key_hash:s.keyHash,user_id:s.userID,page:t,size:l,sort_by:s.sortBy,sort_order:s.sortOrder,expand:s.expand,status:s.status,return_full_object:"true",include_team_keys:"true",include_created_by_keys:"true"}).filter(e=>{let[,t]=e;return null!=t}).map(e=>{let[t,l]=e;return[t,String(l)]})),n="".concat(a?"".concat(a,"/key/list"):"/key/list","?").concat(r),o=await fetch(n,{method:"GET",headers:{[(0,i.getGlobalLitellmHeaderName)()]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,i.deriveErrorMessage)(e);throw(0,i.handleError)(t),Error(t)}let d=await o.json();return console.log("/key/list API Response:",d),d}catch(e){throw console.error("Failed to list keys:",e),e}},c=function(e,t){let l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{accessToken:r}=(0,n.Z)();return(0,s.a)({queryKey:o.list({page:e,limit:t,...l}),queryFn:async()=>await d(r,e,t,l),enabled:!!r,staleTime:3e4,placeholderData:a.Wk})},m=(0,r.n)("deletedKeys"),u=function(e,t){let l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{accessToken:r}=(0,n.Z)();return(0,s.a)({queryKey:m.list({page:e,limit:t,...l}),queryFn:async()=>await d(r,e,t,{...l,status:"deleted"}),enabled:!!r,staleTime:3e4,placeholderData:a.Wk})}},89348:function(e,t,l){l.d(t,{$:function(){return x}});var s=l(57437),a=l(16312),r=l(42264),i=l(65869),n=l(99397),o=l(2265),d=l(37592),c=l(99981),m=l(49322),u=l(15051),h=l(32489);function g(e){let{group:t,onChange:l,availableModels:a,maxFallbacks:r}=e,i=a.filter(e=>e!==t.primaryModel),n=e=>{let s=t.fallbackModels.filter((t,l)=>l!==e);l({...t,fallbackModels:s})},o=t.fallbackModels.length{let s=[...t.fallbackModels];s.includes(e)&&(s=s.filter(t=>t!==e)),l({...t,primaryModel:e,fallbackModels:s})},showSearch:!0,filterOption:(e,t)=>{var l;return(null!==(l=null==t?void 0:t.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:a.map(e=>({label:e,value:e}))}),!t.primaryModel&&(0,s.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-amber-600 text-xs bg-amber-50 p-2 rounded",children:[(0,s.jsx)(m.Z,{className:"w-4 h-4"}),(0,s.jsx)("span",{children:"Select a model to begin configuring fallbacks"})]})]}),(0,s.jsx)("div",{className:"flex items-center justify-center -my-4 z-10",children:(0,s.jsxs)("div",{className:"bg-indigo-50 text-indigo-500 px-4 py-1 rounded-full text-xs font-bold border border-indigo-100 flex items-center gap-2 shadow-sm",children:[(0,s.jsx)(u.Z,{className:"w-4 h-4"}),"IF FAILS, TRY..."]})}),(0,s.jsxs)("div",{className:"transition-opacity duration-300 ".concat(t.primaryModel?"opacity-100":"opacity-50 pointer-events-none"),children:[(0,s.jsxs)("label",{className:"block text-sm font-semibold text-gray-700 mb-2",children:["Fallback Chain ",(0,s.jsx)("span",{className:"text-red-500",children:"*"}),(0,s.jsxs)("span",{className:"text-xs text-gray-500 font-normal ml-2",children:["(Max ",r," fallbacks at a time)"]})]}),(0,s.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 border border-gray-200",children:[(0,s.jsxs)("div",{className:"mb-4",children:[(0,s.jsx)(d.default,{mode:"multiple",className:"w-full",size:"large",placeholder:o?"Select fallback models to add...":"Maximum ".concat(r," fallbacks reached"),value:t.fallbackModels,onChange:e=>{let s=e.slice(0,r);l({...t,fallbackModels:s})},disabled:!t.primaryModel,options:i.map(e=>({label:e,value:e})),optionRender:(e,l)=>{let a=t.fallbackModels.includes(e.value),r=a?t.fallbackModels.indexOf(e.value)+1:null;return(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[a&&null!==r&&(0,s.jsx)("span",{className:"flex items-center justify-center w-5 h-5 rounded bg-indigo-100 text-indigo-600 text-xs font-bold",children:r}),(0,s.jsx)("span",{children:e.label})]})},maxTagCount:"responsive",maxTagPlaceholder:e=>(0,s.jsx)(c.Z,{styles:{root:{pointerEvents:"none"}},title:e.map(e=>{let{value:t}=e;return t}).join(", "),children:(0,s.jsxs)("span",{children:["+",e.length," more"]})}),showSearch:!0,filterOption:(e,t)=>{var l;return(null!==(l=null==t?void 0:t.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())}}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:o?"Search and select multiple models. Selected models will appear below in order. (".concat(t.fallbackModels.length,"/").concat(r," used)"):"Maximum ".concat(r," fallbacks reached. Remove some to add more.")})]}),(0,s.jsx)("div",{className:"space-y-2 min-h-[100px]",children:0===t.fallbackModels.length?(0,s.jsxs)("div",{className:"h-32 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center text-gray-400",children:[(0,s.jsx)("span",{className:"text-sm",children:"No fallback models selected"}),(0,s.jsx)("span",{className:"text-xs mt-1",children:"Add models from the dropdown above"})]}):t.fallbackModels.map((e,t)=>(0,s.jsxs)("div",{className:"group flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200 hover:border-indigo-300 hover:shadow-sm transition-all",children:[(0,s.jsxs)("div",{className:"flex items-center gap-3",children:[(0,s.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded bg-gray-100 text-gray-400 group-hover:text-indigo-500 group-hover:bg-indigo-50",children:(0,s.jsx)("span",{className:"text-xs font-bold",children:t+1})}),(0,s.jsx)("div",{children:(0,s.jsx)("span",{className:"font-medium text-gray-800",children:e})})]}),(0,s.jsx)("button",{type:"button",onClick:()=>n(t),className:"opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-red-500 p-1",children:(0,s.jsx)(h.Z,{className:"w-4 h-4"})})]},"".concat(e,"-").concat(t)))})]})]})]})}function x(e){let{groups:t,onGroupsChange:l,availableModels:d,maxFallbacks:c=5,maxGroups:m=5}=e,[u,h]=(0,o.useState)(t.length>0?t[0].id:"1");(0,o.useEffect)(()=>{t.length>0?t.some(e=>e.id===u)||h(t[0].id):h("1")},[t]);let x=()=>{if(t.length>=m)return;let e=Date.now().toString();l([...t,{id:e,primaryModel:null,fallbackModels:[]}]),h(e)},p=e=>{if(1===t.length){r.ZP.warning("At least one group is required");return}let s=t.filter(t=>t.id!==e);l(s),u===e&&s.length>0&&h(s[s.length-1].id)},y=e=>{l(t.map(t=>t.id===e.id?e:t))},f=t.map((e,l)=>{let a=e.primaryModel?e.primaryModel:"Group ".concat(l+1);return{key:e.id,label:a,closable:t.length>1,children:(0,s.jsx)(g,{group:e,onChange:y,availableModels:d,maxFallbacks:c})}});return 0===t.length?(0,s.jsxs)("div",{className:"text-center py-12 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[(0,s.jsx)("p",{className:"text-gray-500 mb-4",children:"No fallback groups configured"}),(0,s.jsx)(a.z,{variant:"primary",onClick:x,icon:()=>(0,s.jsx)(n.Z,{className:"w-4 h-4"}),children:"Create First Group"})]}):(0,s.jsx)(i.default,{type:"editable-card",activeKey:u,onChange:h,onEdit:(e,l)=>{"add"===l?x():"remove"===l&&t.length>1&&p(e)},items:f,className:"fallback-tabs",tabBarStyle:{marginBottom:0},hideAdd:t.length>=m})}},62099:function(e,t,l){var s=l(57437),a=l(2265),r=l(37592),i=l(99981),n=l(23496),o=l(63709),d=l(15424),c=l(31283);let{Option:m}=r.default;t.Z=e=>{var t;let{form:l,autoRotationEnabled:u,onAutoRotationChange:h,rotationInterval:g,onRotationIntervalChange:x,isCreateMode:p=!1}=e,y=g&&!["7d","30d","90d","180d","365d"].includes(g),[f,j]=(0,a.useState)(y),[b,v]=(0,a.useState)(y?g:""),[_,N]=(0,a.useState)((null==l?void 0:null===(t=l.getFieldValue)||void 0===t?void 0:t.call(l,"duration"))||"");return(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Key Expiry Settings"}),(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,s.jsx)("span",{children:"Expire Key"}),(0,s.jsx)(i.Z,{title:p?"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Leave empty to never expire.":"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Use -1 to never expire.",children:(0,s.jsx)(d.Z,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,s.jsx)(c.o,{name:"duration",placeholder:p?"e.g., 30d or leave empty to never expire":"e.g., 30d or -1 to never expire",className:"w-full",value:_,onValueChange:e=>{N(e),l&&"function"==typeof l.setFieldValue?l.setFieldValue("duration",e):l&&"function"==typeof l.setFieldsValue&&l.setFieldsValue({duration:e})}})]})]}),(0,s.jsx)(n.Z,{}),(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Auto-Rotation Settings"}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,s.jsx)("span",{children:"Enable Auto-Rotation"}),(0,s.jsx)(i.Z,{title:"Key will automatically regenerate at the specified interval for enhanced security.",children:(0,s.jsx)(d.Z,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,s.jsx)(o.Z,{checked:u,onChange:h,size:"default",className:u?"":"bg-gray-400"})]}),u&&(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,s.jsx)("span",{children:"Rotation Interval"}),(0,s.jsx)(i.Z,{title:"How often the key should be automatically rotated. Choose the interval that best fits your security requirements.",children:(0,s.jsx)(d.Z,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)(r.default,{value:f?"custom":g,onChange:e=>{"custom"===e?j(!0):(j(!1),v(""),x(e))},className:"w-full",placeholder:"Select interval",children:[(0,s.jsx)(m,{value:"7d",children:"7 days"}),(0,s.jsx)(m,{value:"30d",children:"30 days"}),(0,s.jsx)(m,{value:"90d",children:"90 days"}),(0,s.jsx)(m,{value:"180d",children:"180 days"}),(0,s.jsx)(m,{value:"365d",children:"365 days"}),(0,s.jsx)(m,{value:"custom",children:"Custom interval"})]}),f&&(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsx)(c.o,{value:b,onChange:e=>{let t=e.target.value;v(t),x(t)},placeholder:"e.g., 1s, 5m, 2h, 14d"}),(0,s.jsx)("div",{className:"text-xs text-gray-500",children:"Supported formats: seconds (s), minutes (m), hours (h), days (d)"})]})]})]})]}),u&&(0,s.jsx)("div",{className:"bg-blue-50 p-3 rounded-md text-sm text-blue-700",children:"When rotation occurs, you'll receive a notification with the new key. The old key will be deactivated after a brief grace period."})]})]})}},72885:function(e,t,l){var s=l(57437),a=l(2265),r=l(77355),i=l(93416),n=l(74998),o=l(95704),d=l(76593),c=l(9114);t.Z=e=>{let{accessToken:t,initialModelAliases:l={},onAliasUpdate:m,showExampleConfig:u=!0}=e,[h,g]=(0,a.useState)([]),[x,p]=(0,a.useState)({aliasName:"",targetModel:""}),[y,f]=(0,a.useState)(null);(0,a.useEffect)(()=>{g(Object.entries(l).map((e,t)=>{let[l,s]=e;return{id:"".concat(t,"-").concat(l),aliasName:l,targetModel:s}}))},[l]);let j=e=>{f({...e})},b=()=>{if(!y)return;if(!y.aliasName||!y.targetModel){c.Z.fromBackend("Please provide both alias name and target model");return}if(h.some(e=>e.id!==y.id&&e.aliasName===y.aliasName)){c.Z.fromBackend("An alias with this name already exists");return}let e=h.map(e=>e.id===y.id?y:e);g(e),f(null);let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),m&&m(t),c.Z.success("Alias updated successfully")},v=()=>{f(null)},_=e=>{let t=h.filter(t=>t.id!==e);g(t);let l={};t.forEach(e=>{l[e.aliasName]=e.targetModel}),m&&m(l),c.Z.success("Alias deleted successfully")},N=h.reduce((e,t)=>(e[t.aliasName]=t.targetModel,e),{});return(0,s.jsxs)("div",{className:"mt-4",children:[(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsx)(o.xv,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,s.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,s.jsx)("input",{type:"text",value:x.aliasName,onChange:e=>p({...x,aliasName:e.target.value}),placeholder:"e.g., gpt-4o",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model"}),(0,s.jsx)(d.Z,{accessToken:t,value:x.targetModel,placeholder:"Select target model",onChange:e=>p({...x,targetModel:e}),showLabel:!1})]}),(0,s.jsx)("div",{className:"flex items-end",children:(0,s.jsxs)("button",{onClick:()=>{if(!x.aliasName||!x.targetModel){c.Z.fromBackend("Please provide both alias name and target model");return}if(h.some(e=>e.aliasName===x.aliasName)){c.Z.fromBackend("An alias with this name already exists");return}let e=[...h,{id:"".concat(Date.now(),"-").concat(x.aliasName),aliasName:x.aliasName,targetModel:x.targetModel}];g(e),p({aliasName:"",targetModel:""});let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),m&&m(t),c.Z.success("Alias added successfully")},disabled:!x.aliasName||!x.targetModel,className:"flex items-center px-4 py-2 rounded-md text-sm ".concat(x.aliasName&&x.targetModel?"bg-green-600 text-white hover:bg-green-700":"bg-gray-300 text-gray-500 cursor-not-allowed"),children:[(0,s.jsx)(r.Z,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,s.jsx)(o.xv,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,s.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,s.jsx)("div",{className:"overflow-x-auto",children:(0,s.jsxs)(o.iA,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,s.jsx)(o.ss,{children:(0,s.jsxs)(o.SC,{children:[(0,s.jsx)(o.xs,{className:"py-1 h-8",children:"Alias Name"}),(0,s.jsx)(o.xs,{className:"py-1 h-8",children:"Target Model"}),(0,s.jsx)(o.xs,{className:"py-1 h-8",children:"Actions"})]})}),(0,s.jsxs)(o.RM,{children:[h.map(e=>(0,s.jsx)(o.SC,{className:"h-8",children:y&&y.id===e.id?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o.pj,{className:"py-0.5",children:(0,s.jsx)("input",{type:"text",value:y.aliasName,onChange:e=>f({...y,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,s.jsx)(o.pj,{className:"py-0.5",children:(0,s.jsx)(d.Z,{accessToken:t,value:y.targetModel,onChange:e=>f({...y,targetModel:e}),showLabel:!1,style:{height:"32px"}})}),(0,s.jsx)(o.pj,{className:"py-0.5 whitespace-nowrap",children:(0,s.jsxs)("div",{className:"flex space-x-2",children:[(0,s.jsx)("button",{onClick:b,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,s.jsx)("button",{onClick:v,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o.pj,{className:"py-0.5 text-sm text-gray-900",children:e.aliasName}),(0,s.jsx)(o.pj,{className:"py-0.5 text-sm text-gray-500",children:e.targetModel}),(0,s.jsx)(o.pj,{className:"py-0.5 whitespace-nowrap",children:(0,s.jsxs)("div",{className:"flex space-x-2",children:[(0,s.jsx)("button",{onClick:()=>j(e),className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,s.jsx)(i.Z,{className:"w-3 h-3"})}),(0,s.jsx)("button",{onClick:()=>_(e.id),className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,s.jsx)(n.Z,{className:"w-3 h-3"})})]})})]})},e.id)),0===h.length&&(0,s.jsx)(o.SC,{children:(0,s.jsx)(o.pj,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),u&&(0,s.jsxs)(o.Zb,{children:[(0,s.jsx)(o.Dx,{className:"mb-4",children:"Configuration Example"}),(0,s.jsx)(o.xv,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config:"}),(0,s.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,s.jsxs)("div",{className:"text-gray-700",children:["model_aliases:",0===Object.keys(N).length?(0,s.jsxs)("span",{className:"text-gray-500",children:[(0,s.jsx)("br",{}),"\xa0\xa0# No aliases configured yet"]}):Object.entries(N).map(e=>{let[t,l]=e;return(0,s.jsxs)("span",{children:[(0,s.jsx)("br",{}),'\xa0\xa0"',t,'": "',l,'"']},t)})]})})]})]})}},76593:function(e,t,l){var s=l(57437),a=l(2265),r=l(56522),i=l(37592),n=l(69993),o=l(10703);t.Z=e=>{let{accessToken:t,value:l,placeholder:d="Select a Model",onChange:c,disabled:m=!1,style:u,className:h,showLabel:g=!0,labelText:x="Select Model"}=e,[p,y]=(0,a.useState)(l),[f,j]=(0,a.useState)(!1),[b,v]=(0,a.useState)([]),_=(0,a.useRef)(null);return(0,a.useEffect)(()=>{y(l)},[l]),(0,a.useEffect)(()=>{t&&(async()=>{try{let e=await (0,o.p)(t);console.log("Fetched models for selector:",e),e.length>0&&v(e)}catch(e){console.error("Error fetching model info:",e)}})()},[t]),(0,s.jsxs)("div",{children:[g&&(0,s.jsxs)(r.x,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,s.jsx)(n.Z,{className:"mr-2"})," ",x]}),(0,s.jsx)(i.default,{value:p,placeholder:d,onChange:e=>{"custom"===e?(j(!0),y(void 0)):(j(!1),y(e),c&&c(e))},options:[...Array.from(new Set(b.map(e=>e.model_group))).map((e,t)=>({value:e,label:e,key:t})),{value:"custom",label:"Enter custom model",key:"custom"}],style:{width:"100%",...u},showSearch:!0,className:"rounded-md ".concat(h||""),disabled:m}),f&&(0,s.jsx)(r.o,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{y(e),c&&c(e)},500)},disabled:m})]})}},2597:function(e,t,l){var s=l(57437);l(2265);var a=l(92280),r=l(54507);t.Z=function(e){let{value:t,onChange:l,premiumUser:i=!1,disabledCallbacks:n=[],onDisabledCallbacksChange:o}=e;return i?(0,s.jsx)(r.Z,{value:t,onChange:l,disabledCallbacks:n,onDisabledCallbacksChange:o}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex flex-wrap gap-2 mb-3",children:[(0,s.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-green-50 border border-green-200 text-green-800 text-sm font-medium opacity-50",children:"✨ langfuse-logging"}),(0,s.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-green-50 border border-green-200 text-green-800 text-sm font-medium opacity-50",children:"✨ datadog-logging"})]}),(0,s.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,s.jsxs)(a.x,{className:"text-sm text-yellow-800",children:["Setting Key/Team logging settings is a LiteLLM Enterprise feature. Global Logging Settings are available for all free users. Get a trial key"," ",(0,s.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})}},65895:function(e,t,l){var s=l(57437);l(2265);var a=l(37592),r=l(10032),i=l(99981),n=l(15424);let{Option:o}=a.default;t.Z=e=>{let{type:t,name:l,showDetailedDescriptions:d=!0,className:c="",initialValue:m=null,form:u,onChange:h}=e,g=t.toUpperCase(),x=t.toLowerCase(),p="Select 'guaranteed_throughput' to prevent overallocating ".concat(g," limit when the key belongs to a Team with specific ").concat(g," limits.");return(0,s.jsx)(r.Z.Item,{label:(0,s.jsxs)("span",{children:[g," Rate Limit Type"," ",(0,s.jsx)(i.Z,{title:p,children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:l,initialValue:m,className:c,children:(0,s.jsx)(a.default,{defaultValue:d?"default":void 0,placeholder:"Select rate limit type",style:{width:"100%"},optionLabelProp:d?"label":void 0,onChange:e=>{u&&u.setFieldValue(l,e),h&&h(e)},children:d?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o,{value:"best_effort_throughput",label:"Default",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,s.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Best effort throughput - no error if we're overallocating ",x," (Team/Key Limits checked at runtime)."]})]})}),(0,s.jsx)(o,{value:"guaranteed_throughput",label:"Guaranteed throughput",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Guaranteed throughput"}),(0,s.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Guaranteed throughput - raise an error if we're overallocating ",x," (also checks model-specific limits)"]})]})}),(0,s.jsx)(o,{value:"dynamic",label:"Dynamic",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Dynamic"}),(0,s.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["If the key has a set ",g," (e.g. 2 ",g,") and there are no 429 errors, it can dynamically exceed the limit when the model being called is not erroring."]})]})})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o,{value:"best_effort_throughput",children:"Best effort throughput"}),(0,s.jsx)(o,{value:"guaranteed_throughput",children:"Guaranteed throughput"}),(0,s.jsx)(o,{value:"dynamic",children:"Dynamic"})]})})})}},76364:function(e,t,l){var s=l(57437),a=l(2265),r=l(58643),i=l(19250),n=l(56334),o=l(89348),d=l(10703);let c=(0,a.forwardRef)((e,t)=>{let{accessToken:l,value:c,onChange:m,modelData:u}=e,[h,g]=(0,a.useState)({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),[x,p]=(0,a.useState)([]),[y,f]=(0,a.useState)([]),[j,b]=(0,a.useState)([]),[v,_]=(0,a.useState)([]),[N,w]=(0,a.useState)({}),[k,S]=(0,a.useState)({}),Z=(0,a.useRef)(!1),C=(0,a.useRef)(null),M=e=>e&&0!==e.length?e.map((e,t)=>{let[l,s]=Object.entries(e)[0];return{id:(t+1).toString(),primaryModel:l||null,fallbackModels:s||[]}}):[{id:"1",primaryModel:null,fallbackModels:[]}],T=e=>e.filter(e=>e.primaryModel&&e.fallbackModels.length>0).map(e=>({[e.primaryModel]:e.fallbackModels}));(0,a.useEffect)(()=>{let e=(null==c?void 0:c.router_settings)?JSON.stringify({routing_strategy:c.router_settings.routing_strategy,fallbacks:c.router_settings.fallbacks,enable_tag_filtering:c.router_settings.enable_tag_filtering}):null;if(Z.current&&e===C.current){Z.current=!1;return}if(Z.current&&e!==C.current&&(Z.current=!1),e!==C.current){if(C.current=e,null==c?void 0:c.router_settings){var t;let e=c.router_settings,{fallbacks:l,...s}=e;g({routerSettings:s,selectedStrategy:e.routing_strategy||null,enableTagFiltering:null!==(t=e.enable_tag_filtering)&&void 0!==t&&t});let a=e.fallbacks||[];p(a),f(M(a))}else g({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),p([]),f([{id:"1",primaryModel:null,fallbackModels:[]}])}},[c]),(0,a.useEffect)(()=>{l&&(0,i.getRouterSettingsCall)(l).then(e=>{if(e.fields){let t={};e.fields.forEach(e=>{t[e.field_name]={ui_field_name:e.ui_field_name,field_description:e.field_description,options:e.options,link:e.link}}),w(t);let l=e.fields.find(e=>"routing_strategy"===e.field_name);(null==l?void 0:l.options)&&_(l.options),e.routing_strategy_descriptions&&S(e.routing_strategy_descriptions)}})},[l]),(0,a.useEffect)(()=>{l&&(async()=>{try{let e=await (0,d.p)(l);b(e)}catch(e){console.error("Error fetching model info for fallbacks:",e)}})()},[l]);let L=()=>{let e=new Set(["allowed_fails","cooldown_time","num_retries","timeout","retry_after"]),t=new Set(["model_group_alias","retry_policy"]),l=(l,s,a)=>{if(null==s)return a;let r=String(s).trim();if(""===r||"null"===r.toLowerCase())return null;if(e.has(l)){let e=Number(r);return Number.isNaN(e)?a:e}if(t.has(l)){if(""===r)return null;try{return JSON.parse(r)}catch(e){return a}}return"true"===r.toLowerCase()||"false"!==r.toLowerCase()&&r},s=Object.fromEntries(Object.entries({...h.routerSettings,enable_tag_filtering:h.enableTagFiltering,routing_strategy:h.selectedStrategy,fallbacks:x.length>0?x:null}).map(e=>{let[t,s]=e;if("routing_strategy_args"!==t&&"routing_strategy"!==t&&"enable_tag_filtering"!==t&&"fallbacks"!==t){let e=document.querySelector('input[name="'.concat(t,'"]'));if(e&&void 0!==e.value&&""!==e.value){let a=l(t,e.value,s);return[t,a]}}else if("routing_strategy"===t)return[t,h.selectedStrategy];else if("enable_tag_filtering"===t)return[t,h.enableTagFiltering];else if("fallbacks"===t)return[t,x.length>0?x:null];else if("routing_strategy_args"===t&&"latency-based-routing"===h.selectedStrategy){let e=document.querySelector('input[name="lowest_latency_buffer"]'),t=document.querySelector('input[name="ttl"]'),l={};return(null==e?void 0:e.value)&&(l.lowest_latency_buffer=Number(e.value)),(null==t?void 0:t.value)&&(l.ttl=Number(t.value)),["routing_strategy_args",Object.keys(l).length>0?l:null]}return[t,s]}).filter(e=>null!=e)),a=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return null==e||"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length||t&&("number"!=typeof e||Number.isNaN(e))?null:e};return{routing_strategy:a(s.routing_strategy),allowed_fails:a(s.allowed_fails,!0),cooldown_time:a(s.cooldown_time,!0),num_retries:a(s.num_retries,!0),timeout:a(s.timeout,!0),retry_after:a(s.retry_after,!0),fallbacks:x.length>0?x:null,context_window_fallbacks:a(s.context_window_fallbacks),retry_policy:a(s.retry_policy),model_group_alias:a(s.model_group_alias),enable_tag_filtering:h.enableTagFiltering,routing_strategy_args:a(s.routing_strategy_args)}};(0,a.useEffect)(()=>{if(!m)return;let e=setTimeout(()=>{Z.current=!0,m({router_settings:L()})},100);return()=>clearTimeout(e)},[h,x]);let F=Array.from(new Set(j.map(e=>e.model_group))).sort();return((0,a.useImperativeHandle)(t,()=>({getValue:()=>({router_settings:L()})})),l)?(0,s.jsx)("div",{className:"w-full",children:(0,s.jsxs)(r.v0,{className:"w-full",children:[(0,s.jsxs)(r.td,{variant:"line",defaultValue:"1",className:"px-8 pt-4",children:[(0,s.jsx)(r.OK,{value:"1",children:"Loadbalancing"}),(0,s.jsx)(r.OK,{value:"2",children:"Fallbacks"})]}),(0,s.jsxs)(r.nP,{className:"px-8 py-6",children:[(0,s.jsx)(r.x4,{children:(0,s.jsx)(n.Z,{value:h,onChange:g,routerFieldsMetadata:N,availableRoutingStrategies:v,routingStrategyDescriptions:k})}),(0,s.jsx)(r.x4,{children:(0,s.jsx)(o.$,{groups:y,onGroupsChange:e=>{f(e),p(T(e))},availableModels:F,maxFallbacks:5,maxGroups:5})})]})]})}):null});c.displayName="RouterSettingsAccordion",t.Z=c},71098:function(e,t,l){l.d(t,{ZP:function(){return et},wk:function(){return X},Nr:function(){return ee}});var s=l(57437),a=l(30280),r=l(39760),i=l(59872),n=l(15424),o=l(29827),d=l(87452),c=l(88829),m=l(72208),u=l(78489),h=l(49804),g=l(67101),x=l(84264),p=l(49566),y=l(96761),f=l(37592),j=l(10032),b=l(22116),v=l(99981),_=l(29967),N=l(5545),w=l(63709),k=l(4260),S=l(7310),Z=l.n(S),C=l(2265),M=l(29233),T=l(20347),L=l(82586),F=l(97434),P=l(65925),A=l(63610),E=l(62099),I=l(72885),V=l(95096),R=l(2597),O=l(65895),D=l(76364),K=l(84376),U=l(7765),q=l(46468),B=l(97492),G=l(68473),z=l(9114),J=l(19250),W=l(24199),H=l(97415);let Y=e=>{let t;if(!(t=!e||"object"!=typeof e||e instanceof Error?String(e):JSON.stringify(e)).includes("/key/generate")&&!t.includes("KeyManagementRoutes.KEY_GENERATE"))return"Error creating the key: ".concat(e);let l=t;try{if(!e||"object"!=typeof e||e instanceof Error){let e=t.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]),s=(null==t?void 0:t.error)||t;(null==s?void 0:s.message)&&(l=s.message)}}else{let t=(null==e?void 0:e.error)||e;(null==t?void 0:t.message)&&(l=t.message)}}catch(e){}return t.includes("team_member_permission_error")||l.includes("Team member does not have permissions")?"Team member does not have permission to generate key for this team. Ask your proxy admin to configure the team member permission settings.":"Error creating the key: ".concat(e)},{Option:$}=f.default,Q=e=>{let t=[];if(console.log("data:",JSON.stringify(e)),e)for(let l of e)l.metadata&&l.metadata.tags&&t.push(...l.metadata.tags);let l=Array.from(new Set(t)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",l),l},X=async(e,t,l,s)=>{try{if(null===e||null===t)return[];if(null!==l){let a=(await (0,J.modelAvailableCall)(l,e,t,!0,s,!0)).data.map(e=>e.id);return console.log("available_model_names:",a),a}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},ee=async(e,t,l,s)=>{try{if(null===e||null===t)return;if(null!==l){let a=(await (0,J.modelAvailableCall)(l,e,t)).data.map(e=>e.id);console.log("available_model_names:",a),s(a)}}catch(e){console.error("Error fetching user models:",e)}};var et=e=>{let{team:t,teams:l,data:S,addKey:et}=e,{accessToken:el,userId:es,userRole:ea,premiumUser:er}=(0,r.Z)(),ei=(0,o.NL)(),[en]=j.Z.useForm(),[eo,ed]=(0,C.useState)(!1),[ec,em]=(0,C.useState)(null),[eu,eh]=(0,C.useState)(null),[eg,ex]=(0,C.useState)([]),[ep,ey]=(0,C.useState)([]),[ef,ej]=(0,C.useState)("you"),[eb,ev]=(0,C.useState)(Q(S)),[e_,eN]=(0,C.useState)([]),[ew,ek]=(0,C.useState)([]),[eS,eZ]=(0,C.useState)([]),[eC,eM]=(0,C.useState)([]),[eT,eL]=(0,C.useState)(t),[eF,eP]=(0,C.useState)(!1),[eA,eE]=(0,C.useState)(null),[eI,eV]=(0,C.useState)({}),[eR,eO]=(0,C.useState)([]),[eD,eK]=(0,C.useState)(!1),[eU,eq]=(0,C.useState)([]),[eB,eG]=(0,C.useState)([]),[ez,eJ]=(0,C.useState)("llm_api"),[eW,eH]=(0,C.useState)({}),[eY,e$]=(0,C.useState)(!1),[eQ,eX]=(0,C.useState)("30d"),[e0,e4]=(0,C.useState)(null),[e1,e2]=(0,C.useState)(0),e5=()=>{ed(!1),en.resetFields(),eM([]),eG([]),eJ("llm_api"),eH({}),e$(!1),eX("30d"),e4(null),e2(e=>e+1)},e3=()=>{ed(!1),em(null),eL(null),en.resetFields(),eM([]),eG([]),eJ("llm_api"),eH({}),e$(!1),eX("30d"),e4(null),e2(e=>e+1)};(0,C.useEffect)(()=>{es&&ea&&el&&ee(es,ea,el,ex)},[el,es,ea]),(0,C.useEffect)(()=>{let e=async()=>{try{let e=(await (0,J.getPoliciesList)(el)).policies.map(e=>e.policy_name);ek(e)}catch(e){console.error("Failed to fetch policies:",e)}},t=async()=>{try{let e=await (0,J.getPromptsList)(el);eZ(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}};(async()=>{try{let e=(await (0,J.getGuardrailsList)(el)).guardrails.map(e=>e.guardrail_name);eN(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e(),t()},[el]),(0,C.useEffect)(()=>{(async()=>{try{if(el){let e=sessionStorage.getItem("possibleUserRoles");if(e)eV(JSON.parse(e));else{let e=await (0,J.getPossibleUserRoles)(el);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),eV(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[el]);let e7=ep.includes("no-default-models")&&!eT,e6=async e=>{try{var t,l,s,r,i,n,o;let d;let c=null!==(i=null==e?void 0:e.key_alias)&&void 0!==i?i:"",m=null!==(n=null==e?void 0:e.team_id)&&void 0!==n?n:null;if((null!==(o=null==S?void 0:S.filter(e=>e.team_id===m).map(e=>e.key_alias))&&void 0!==o?o:[]).includes(c))throw Error("Key alias ".concat(c," already exists for team with ID ").concat(m,", please provide another key alias"));z.Z.info("Making API Call"),ed(!0),"you"===ef&&(e.user_id=es);let u={};try{u=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}if("service_account"===ef&&(u.service_account_id=e.key_alias),eC.length>0&&(u={...u,logging:eC.filter(e=>e.callback_name)}),eB.length>0){let e=(0,F.Z3)(eB);u={...u,litellm_disabled_callbacks:e}}if(eY&&(e.auto_rotate=!0,e.rotation_interval=eQ),e.duration&&""!==e.duration.trim()||(e.duration=null),e.metadata=JSON.stringify(u),e.allowed_vector_store_ids&&e.allowed_vector_store_ids.length>0&&(e.object_permission={vector_stores:e.allowed_vector_store_ids},delete e.allowed_vector_store_ids),e.allowed_mcp_servers_and_groups&&((null===(t=e.allowed_mcp_servers_and_groups.servers)||void 0===t?void 0:t.length)>0||(null===(l=e.allowed_mcp_servers_and_groups.accessGroups)||void 0===l?void 0:l.length)>0)){e.object_permission||(e.object_permission={});let{servers:t,accessGroups:l}=e.allowed_mcp_servers_and_groups;t&&t.length>0&&(e.object_permission.mcp_servers=t),l&&l.length>0&&(e.object_permission.mcp_access_groups=l),delete e.allowed_mcp_servers_and_groups}let h=e.mcp_tool_permissions||{};if(Object.keys(h).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=h),delete e.mcp_tool_permissions,e.allowed_mcp_access_groups&&e.allowed_mcp_access_groups.length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_access_groups=e.allowed_mcp_access_groups,delete e.allowed_mcp_access_groups),e.allowed_agents_and_groups&&((null===(s=e.allowed_agents_and_groups.agents)||void 0===s?void 0:s.length)>0||(null===(r=e.allowed_agents_and_groups.accessGroups)||void 0===r?void 0:r.length)>0)){e.object_permission||(e.object_permission={});let{agents:t,accessGroups:l}=e.allowed_agents_and_groups;t&&t.length>0&&(e.object_permission.agents=t),l&&l.length>0&&(e.object_permission.agent_access_groups=l),delete e.allowed_agents_and_groups}Object.keys(eW).length>0&&(e.aliases=JSON.stringify(eW)),(null==e0?void 0:e0.router_settings)&&Object.values(e0.router_settings).some(e=>null!=e&&""!==e)&&(e.router_settings=e0.router_settings),d="service_account"===ef?await (0,J.keyCreateServiceAccountCall)(el,e):await (0,J.keyCreateCall)(el,es,e),console.log("key create Response:",d),et(d),ei.invalidateQueries({queryKey:a.Km.lists()}),em(d.key),eh(d.soft_budget),z.Z.success("Virtual Key Created"),en.resetFields(),localStorage.removeItem("userData"+es)}catch(t){console.log("error in create key:",t);let e=Y(t);z.Z.fromBackend(e)}};(0,C.useEffect)(()=>{if(es&&ea&&el){var e;X(es,ea,el,null!==(e=null==eT?void 0:eT.team_id)&&void 0!==e?e:null).then(e=>{var t;ey(Array.from(new Set([...null!==(t=null==eT?void 0:eT.models)&&void 0!==t?t:[],...e])))})}en.setFieldValue("models",[])},[eT,el,es,ea]);let e9=async e=>{if(!e){eO([]);return}eK(!0);try{let t=new URLSearchParams;if(t.append("user_email",e),null==el)return;let l=(await (0,J.userFilterUICall)(el,t)).map(e=>({label:"".concat(e.user_email," (").concat(e.user_id,")"),value:e.user_id,user:e}));eO(l)}catch(e){console.error("Error fetching users:",e),z.Z.fromBackend("Failed to search for users")}finally{eK(!1)}},e8=(0,C.useCallback)(Z()(e=>e9(e),300),[el]),te=(e,t)=>{let l=t.user;en.setFieldsValue({user_id:l.user_id})};return(0,s.jsxs)("div",{children:[ea&&T.LQ.includes(ea)&&(0,s.jsx)(u.Z,{className:"mx-auto",onClick:()=>ed(!0),children:"+ Create New Key"}),(0,s.jsx)(b.Z,{open:eo,width:1e3,footer:null,onOk:e5,onCancel:e3,children:(0,s.jsxs)(j.Z,{form:en,onFinish:e6,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsxs)("div",{className:"mb-8",children:[(0,s.jsx)(y.Z,{className:"mb-4",children:"Key Ownership"}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Owned By"," ",(0,s.jsx)(v.Z,{title:"Select who will own this Virtual Key",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,s.jsxs)(_.ZP.Group,{onChange:e=>ej(e.target.value),value:ef,children:[(0,s.jsx)(_.ZP,{value:"you",children:"You"}),(0,s.jsx)(_.ZP,{value:"service_account",children:"Service Account"}),"Admin"===ea&&(0,s.jsx)(_.ZP,{value:"another_user",children:"Another User"})]})}),"another_user"===ef&&(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["User ID"," ",(0,s.jsx)(v.Z,{title:"The user who will own this key and be responsible for its usage",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===ef,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,s.jsx)(f.default,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{e8(e)},onSelect:(e,t)=>te(e,t),options:eR,loading:eD,allowClear:!0,style:{width:"100%"},notFoundContent:eD?"Searching...":"No users found"}),(0,s.jsx)(N.ZP,{onClick:()=>eP(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,s.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Team"," ",(0,s.jsx)(v.Z,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:t?t.team_id:null,className:"mt-4",rules:[{required:"service_account"===ef,message:"Please select a team for the service account"}],help:"service_account"===ef?"required":"",children:(0,s.jsx)(K.Z,{teams:l,onChange:e=>{eL((null==l?void 0:l.find(t=>t.team_id===e))||null)}})})]}),e7&&(0,s.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,s.jsx)(x.Z,{className:"text-blue-800 text-sm",children:"Please select a team to continue configuring your Virtual Key. If you do not see any teams, please contact your Proxy Admin to either provide you with access to models or to add you to a team."})}),!e7&&(0,s.jsxs)("div",{className:"mb-8",children:[(0,s.jsx)(y.Z,{className:"mb-4",children:"Key Details"}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["you"===ef||"another_user"===ef?"Key Name":"Service Account ID"," ",(0,s.jsx)(v.Z,{title:"you"===ef||"another_user"===ef?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:"Please input a ".concat("you"===ef?"key name":"service account ID")}],help:"required",children:(0,s.jsx)(p.Z,{placeholder:""})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(v.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,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"models",rules:"management"===ez||"read_only"===ez?[]:[{required:!0,message:"Please select a model"}],help:"management"===ez||"read_only"===ez?"Models field is disabled for this key type":"required",className:"mt-4",children:(0,s.jsxs)(f.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:"management"===ez||"read_only"===ez,onChange:e=>{e.includes("all-team-models")&&en.setFieldsValue({models:["all-team-models"]})},children:[(0,s.jsx)($,{value:"all-team-models",children:"All Team Models"},"all-team-models"),ep.map(e=>(0,s.jsx)($,{value:e,children:(0,q.W0)(e)},e))]})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Key Type"," ",(0,s.jsx)(v.Z,{title:"Select the type of key to determine what routes and operations this key can access",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"key_type",initialValue:"llm_api",className:"mt-4",children:(0,s.jsxs)(f.default,{defaultValue:"llm_api",placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",onChange:e=>{eJ(e),("management"===e||"read_only"===e)&&en.setFieldsValue({models:[]})},children:[(0,s.jsx)($,{value:"default",label:"Default",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,s.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call LLM API + Management routes"})]})}),(0,s.jsx)($,{value:"llm_api",label:"LLM API",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"LLM API"}),(0,s.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only LLM API routes (chat/completions, embeddings, etc.)"})]})}),(0,s.jsx)($,{value:"management",label:"Management",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,s.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})})]}),!e7&&(0,s.jsx)("div",{className:"mb-8",children:(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)(y.Z,{className:"m-0",children:"Optional Settings"})}),(0,s.jsxs)(c.Z,{children:[(0,s.jsx)(j.Z.Item,{className:"mt-4",label:(0,s.jsxs)("span",{children:["Max Budget (USD)"," ",(0,s.jsx)(v.Z,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:"Budget cannot exceed team max budget: $".concat((null==t?void 0:t.max_budget)!==null&&(null==t?void 0:t.max_budget)!==void 0?null==t?void 0:t.max_budget:"unlimited"),rules:[{validator:async(e,l)=>{if(l&&t&&null!==t.max_budget&&l>t.max_budget)throw Error("Budget cannot exceed team max budget: $".concat((0,i.pw)(t.max_budget,4)))}}],children:(0,s.jsx)(W.Z,{step:.01,precision:2,width:200})}),(0,s.jsx)(j.Z.Item,{className:"mt-4",label:(0,s.jsxs)("span",{children:["Reset Budget"," ",(0,s.jsx)(v.Z,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:"Team Reset Budget: ".concat((null==t?void 0:t.budget_duration)!==null&&(null==t?void 0:t.budget_duration)!==void 0?null==t?void 0:t.budget_duration:"None"),children:(0,s.jsx)(P.Z,{onChange:e=>en.setFieldValue("budget_duration",e)})}),(0,s.jsx)(j.Z.Item,{className:"mt-4",label:(0,s.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,s.jsx)(v.Z,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:"TPM cannot exceed team TPM limit: ".concat((null==t?void 0:t.tpm_limit)!==null&&(null==t?void 0:t.tpm_limit)!==void 0?null==t?void 0:t.tpm_limit:"unlimited"),rules:[{validator:async(e,l)=>{if(l&&t&&null!==t.tpm_limit&&l>t.tpm_limit)throw Error("TPM limit cannot exceed team TPM limit: ".concat(t.tpm_limit))}}],children:(0,s.jsx)(W.Z,{step:1,width:400})}),(0,s.jsx)(O.Z,{type:"tpm",name:"tpm_limit_type",className:"mt-4",initialValue:null,form:en,showDetailedDescriptions:!0}),(0,s.jsx)(j.Z.Item,{className:"mt-4",label:(0,s.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,s.jsx)(v.Z,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:"RPM cannot exceed team RPM limit: ".concat((null==t?void 0:t.rpm_limit)!==null&&(null==t?void 0:t.rpm_limit)!==void 0?null==t?void 0:t.rpm_limit:"unlimited"),rules:[{validator:async(e,l)=>{if(l&&t&&null!==t.rpm_limit&&l>t.rpm_limit)throw Error("RPM limit cannot exceed team RPM limit: ".concat(t.rpm_limit))}}],children:(0,s.jsx)(W.Z,{step:1,width:400})}),(0,s.jsx)(O.Z,{type:"rpm",name:"rpm_limit_type",className:"mt-4",initialValue:null,form:en,showDetailedDescriptions:!0}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Guardrails"," ",(0,s.jsx)(v.Z,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:er?"Select existing guardrails or enter new ones":"Premium feature - Upgrade to set guardrails by key",children:(0,s.jsx)(f.default,{mode:"tags",style:{width:"100%"},disabled:!er,placeholder:er?"Select or enter guardrails":"Premium feature - Upgrade to set guardrails by key",options:e_.map(e=>({value:e,label:e}))})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,s.jsx)(v.Z,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:er?"Bypass global guardrails for this key":"Premium feature - Upgrade to disable global guardrails by key",children:(0,s.jsx)(w.Z,{disabled:!er,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Policies"," ",(0,s.jsx)(v.Z,{title:"Apply policies to this key to control guardrails and other settings",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-4",help:er?"Select existing policies or enter new ones":"Premium feature - Upgrade to set policies by key",children:(0,s.jsx)(f.default,{mode:"tags",style:{width:"100%"},disabled:!er,placeholder:er?"Select or enter policies":"Premium feature - Upgrade to set policies by key",options:ew.map(e=>({value:e,label:e}))})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Prompts"," ",(0,s.jsx)(v.Z,{title:"Allow this key to use specific prompt templates",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/prompt_management",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"prompts",className:"mt-4",help:er?"Select existing prompts or enter new ones":"Premium feature - Upgrade to set prompts by key",children:(0,s.jsx)(f.default,{mode:"tags",style:{width:"100%"},disabled:!er,placeholder:er?"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:eS.map(e=>({value:e,label:e}))})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Allowed Pass Through Routes"," ",(0,s.jsx)(v.Z,{title:"Allow this key to use specific pass through routes",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"allowed_passthrough_routes",className:"mt-4",help:er?"Select existing pass through routes or enter new ones":"Premium feature - Upgrade to set pass through routes by key",children:(0,s.jsx)(V.Z,{onChange:e=>en.setFieldValue("allowed_passthrough_routes",e),value:en.getFieldValue("allowed_passthrough_routes"),accessToken:el,placeholder:er?"Select or enter pass through routes":"Premium feature - Upgrade to set pass through routes by key",disabled:!er,teamId:eT?eT.team_id:null})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,s.jsx)(v.Z,{title:"Select which vector stores this key can access. If none selected, the key will have access to all available vector stores",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_vector_store_ids",className:"mt-4",help:"Select vector stores this key can access. Leave empty for access to all vector stores",children:(0,s.jsx)(H.Z,{onChange:e=>en.setFieldValue("allowed_vector_store_ids",e),value:en.getFieldValue("allowed_vector_store_ids"),accessToken:el,placeholder:"Select vector stores (optional)"})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Metadata"," ",(0,s.jsx)(v.Z,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,s.jsx)(k.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Tags"," ",(0,s.jsx)(v.Z,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,s.jsx)(f.default,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:eb})}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"MCP Settings"})}),(0,s.jsxs)(c.Z,{children:[(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,s.jsx)(v.Z,{title:"Select which MCP servers or access groups this key can access",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",help:"Select MCP servers or access groups this key can access",children:(0,s.jsx)(B.Z,{onChange:e=>en.setFieldValue("allowed_mcp_servers_and_groups",e),value:en.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:el,placeholder:"Select MCP servers or access groups (optional)"})}),(0,s.jsx)(j.Z.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,s.jsx)(k.default,{type:"hidden"})}),(0,s.jsx)(j.Z.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.allowed_mcp_servers_and_groups!==t.allowed_mcp_servers_and_groups||e.mcp_tool_permissions!==t.mcp_tool_permissions,children:()=>{var e;return(0,s.jsx)("div",{className:"mt-6",children:(0,s.jsx)(G.Z,{accessToken:el,selectedServers:(null===(e=en.getFieldValue("allowed_mcp_servers_and_groups"))||void 0===e?void 0:e.servers)||[],toolPermissions:en.getFieldValue("mcp_tool_permissions")||{},onChange:e=>en.setFieldsValue({mcp_tool_permissions:e})})})}})]})]}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Agent Settings"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Allowed Agents"," ",(0,s.jsx)(v.Z,{title:"Select which agents or access groups this key can access",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",help:"Select agents or access groups this key can access",children:(0,s.jsx)(L.Z,{onChange:e=>en.setFieldValue("allowed_agents_and_groups",e),value:en.getFieldValue("allowed_agents_and_groups"),accessToken:el,placeholder:"Select agents or access groups (optional)"})})})]}),er?(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Logging Settings"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(R.Z,{value:eC,onChange:eM,premiumUser:!0,disabledCallbacks:eB,onDisabledCallbacksChange:eG})})})]}):(0,s.jsx)(v.Z,{title:(0,s.jsxs)("span",{children:["Key-level logging settings is an enterprise feature, get in touch -",(0,s.jsx)("a",{href:"https://www.litellm.ai/enterprise",target:"_blank",children:"https://www.litellm.ai/enterprise"})]}),placement:"top",children:(0,s.jsxs)("div",{style:{position:"relative"},children:[(0,s.jsx)("div",{style:{opacity:.5},children:(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Logging Settings"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(R.Z,{value:eC,onChange:eM,premiumUser:!1,disabledCallbacks:eB,onDisabledCallbacksChange:eG})})})]})}),(0,s.jsx)("div",{style:{position:"absolute",inset:0,cursor:"not-allowed"}})]})}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Router Settings"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)("div",{className:"mt-4 w-full",children:(0,s.jsx)(D.Z,{accessToken:el||"",value:e0||void 0,onChange:e4,modelData:eg.length>0?{data:eg.map(e=>({model_name:e}))}:void 0},e1)})})]},"router-settings-accordion-".concat(e1)),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Model Aliases"})}),(0,s.jsx)(c.Z,{children:(0,s.jsxs)("div",{className:"mt-4",children:[(0,s.jsx)(x.Z,{className:"text-sm text-gray-600 mb-4",children:"Create custom aliases for models that can be used in API calls. This allows you to create shortcuts for specific models."}),(0,s.jsx)(I.Z,{accessToken:el,initialModelAliases:eW,onAliasUpdate:eH,showExampleConfig:!1})]})})]}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Key Lifecycle"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(E.Z,{form:en,autoRotationEnabled:eY,onAutoRotationChange:e$,rotationInterval:eQ,onRotationIntervalChange:eX,isCreateMode:!0})})}),(0,s.jsx)(j.Z.Item,{name:"duration",hidden:!0,initialValue:null,children:(0,s.jsx)(k.default,{})})]}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("b",{children:"Advanced Settings"}),(0,s.jsx)(v.Z,{title:(0,s.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,s.jsx)("a",{href:J.proxyBaseUrl?"".concat(J.proxyBaseUrl,"/#/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,s.jsx)(n.Z,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)(A.Z,{schemaComponent:"GenerateKeyRequest",form:en,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(N.ZP,{htmlType:"submit",disabled:e7,style:{opacity:e7?.5:1},children:"Create Key"})})]})}),eF&&(0,s.jsx)(b.Z,{title:"Create New User",visible:eF,onCancel:()=>eP(!1),footer:null,width:800,children:(0,s.jsx)(U.Z,{userID:es,accessToken:el,teams:l,possibleUIRoles:eI,onUserCreated:e=>{eE(e),en.setFieldsValue({user_id:e}),eP(!1)},isEmbedded:!0})}),ec&&(0,s.jsx)(b.Z,{visible:eo,onOk:e5,onCancel:e3,footer:null,children:(0,s.jsxs)(g.Z,{numItems:1,className:"gap-2 w-full",children:[(0,s.jsx)(y.Z,{children:"Save your Key"}),(0,s.jsx)(h.Z,{numColSpan:1,children:(0,s.jsxs)("p",{children:["Please save this secret key somewhere safe and accessible. For security reasons,"," ",(0,s.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,s.jsx)(h.Z,{numColSpan:1,children:null!=ec?(0,s.jsxs)("div",{children:[(0,s.jsx)(x.Z,{className:"mt-3",children:"Virtual Key:"}),(0,s.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,s.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:ec})}),(0,s.jsx)(M.CopyToClipboard,{text:ec,onCopy:()=>{z.Z.success("Virtual Key copied to clipboard")},children:(0,s.jsx)(u.Z,{className:"mt-3",children:"Copy Virtual Key"})})]}):(0,s.jsx)(x.Z,{children:"Key being created, this might take 30s"})})]})})]})}},56334:function(e,t,l){l.d(t,{Z:function(){return u}});var s=l(57437);l(2265);var a=l(31283);let r={ttl:3600,lowest_latency_buffer:0};var i=e=>{let{routingStrategyArgs:t}=e,l={ttl:"Sliding window to look back over when calculating the average latency of a deployment. Default - 1 hour (in seconds).",lowest_latency_buffer:"Shuffle between deployments within this % of the lowest latency. Default - 0 (i.e. always pick lowest latency)."};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"max-w-3xl",children:[(0,s.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Latency-Based Configuration"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Fine-tune latency-based routing behavior"})]}),(0,s.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(t||r).map(e=>{let[t,r]=e;return(0,s.jsx)("div",{className:"space-y-2",children:(0,s.jsxs)("label",{className:"block",children:[(0,s.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:t.replace(/_/g," ")}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l[t]||""}),(0,s.jsx)(a.o,{name:t,defaultValue:"object"==typeof r?JSON.stringify(r,null,2):null==r?void 0:r.toString(),className:"font-mono text-sm w-full"})]})},t)})})]}),(0,s.jsx)("div",{className:"border-t border-gray-200"})]})},n=e=>{let{routerSettings:t,routerFieldsMetadata:l}=e;return(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"max-w-3xl",children:[(0,s.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Reliability & Retries"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure retry logic and failure handling"})]}),(0,s.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(t).filter(e=>{let[t,l]=e;return"fallbacks"!=t&&"context_window_fallbacks"!=t&&"routing_strategy_args"!=t&&"routing_strategy"!=t&&"enable_tag_filtering"!=t}).map(e=>{var t,r;let[i,n]=e;return(0,s.jsx)("div",{className:"space-y-2",children:(0,s.jsxs)("label",{className:"block",children:[(0,s.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:(null===(t=l[i])||void 0===t?void 0:t.ui_field_name)||i}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:(null===(r=l[i])||void 0===r?void 0:r.field_description)||""}),(0,s.jsx)(a.o,{name:i,defaultValue:null==n||"null"===n?"":"object"==typeof n?JSON.stringify(n,null,2):(null==n?void 0:n.toString())||"",placeholder:"—",className:"font-mono text-sm w-full"})]})},i)})})]})},o=l(37592),d=e=>{var t,l;let{selectedStrategy:a,availableStrategies:r,routingStrategyDescriptions:i,routerFieldsMetadata:n,onStrategyChange:d}=e;return(0,s.jsxs)("div",{className:"space-y-2 max-w-3xl",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:(null===(t=n.routing_strategy)||void 0===t?void 0:t.ui_field_name)||"Routing Strategy"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:(null===(l=n.routing_strategy)||void 0===l?void 0:l.field_description)||""})]}),(0,s.jsx)("div",{className:"routing-strategy-select max-w-3xl",children:(0,s.jsx)(o.default,{value:a,onChange:d,style:{width:"100%"},size:"large",children:r.map(e=>(0,s.jsx)(o.default.Option,{value:e,label:e,children:(0,s.jsxs)("div",{className:"flex flex-col gap-0.5 py-1",children:[(0,s.jsx)("span",{className:"font-mono text-sm font-medium",children:e}),i[e]&&(0,s.jsx)("span",{className:"text-xs text-gray-500 font-normal",children:i[e]})]})},e))})})]})},c=l(59341),m=e=>{var t,l,a;let{enabled:r,routerFieldsMetadata:i,onToggle:n}=e;return(0,s.jsx)("div",{className:"space-y-3 max-w-3xl",children:(0,s.jsxs)("div",{className:"flex items-start justify-between",children:[(0,s.jsxs)("div",{className:"flex-1",children:[(0,s.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:(null===(t=i.enable_tag_filtering)||void 0===t?void 0:t.ui_field_name)||"Enable Tag Filtering"}),(0,s.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:[(null===(l=i.enable_tag_filtering)||void 0===l?void 0:l.field_description)||"",(null===(a=i.enable_tag_filtering)||void 0===a?void 0:a.link)&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:i.enable_tag_filtering.link,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"Learn more"})]})]})]}),(0,s.jsx)(c.Z,{checked:r,onChange:n,className:"ml-4"})]})})},u=e=>{let{value:t,onChange:l,routerFieldsMetadata:a,availableRoutingStrategies:r,routingStrategyDescriptions:o}=e;return(0,s.jsxs)("div",{className:"w-full space-y-8 py-2",children:[(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"max-w-3xl",children:[(0,s.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Routing Settings"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure how requests are routed to deployments"})]}),r.length>0&&(0,s.jsx)(d,{selectedStrategy:t.selectedStrategy||t.routerSettings.routing_strategy||null,availableStrategies:r,routingStrategyDescriptions:o,routerFieldsMetadata:a,onStrategyChange:e=>{l({...t,selectedStrategy:e})}}),(0,s.jsx)(m,{enabled:t.enableTagFiltering,routerFieldsMetadata:a,onToggle:e=>{l({...t,enableTagFiltering:e})}})]}),(0,s.jsx)("div",{className:"border-t border-gray-200"}),"latency-based-routing"===t.selectedStrategy&&(0,s.jsx)(i,{routingStrategyArgs:t.routerSettings.routing_strategy_args}),(0,s.jsx)(n,{routerSettings:t.routerSettings,routerFieldsMetadata:a})]})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1098-a265a62173054269.js b/litellm/proxy/_experimental/out/_next/static/chunks/1098-a265a62173054269.js new file mode 100644 index 00000000000..d810749d7e3 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1098-a265a62173054269.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1098],{30280:function(e,t,l){l.d(t,{EX:function(){return c},Km:function(){return o},Tv:function(){return u}});var s=l(11713),a=l(45345),r=l(90246),i=l(19250),n=l(80443);let o=(0,r.n)("keys"),d=async function(e,t,l){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};try{let a=(0,i.getProxyBaseUrl)(),r=new URLSearchParams(Object.entries({team_id:s.teamID,organization_id:s.organizationID,key_alias:s.selectedKeyAlias,key_hash:s.keyHash,user_id:s.userID,page:t,size:l,sort_by:s.sortBy,sort_order:s.sortOrder,expand:s.expand,status:s.status,return_full_object:"true",include_team_keys:"true",include_created_by_keys:"true"}).filter(e=>{let[,t]=e;return null!=t}).map(e=>{let[t,l]=e;return[t,String(l)]})),n="".concat(a?"".concat(a,"/key/list"):"/key/list","?").concat(r),o=await fetch(n,{method:"GET",headers:{[(0,i.getGlobalLitellmHeaderName)()]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,i.deriveErrorMessage)(e);throw(0,i.handleError)(t),Error(t)}let d=await o.json();return console.log("/key/list API Response:",d),d}catch(e){throw console.error("Failed to list keys:",e),e}},c=function(e,t){let l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{accessToken:r}=(0,n.Z)();return(0,s.a)({queryKey:o.list({page:e,limit:t,...l}),queryFn:async()=>await d(r,e,t,l),enabled:!!r,staleTime:3e4,placeholderData:a.Wk})},m=(0,r.n)("deletedKeys"),u=function(e,t){let l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{accessToken:r}=(0,n.Z)();return(0,s.a)({queryKey:m.list({page:e,limit:t,...l}),queryFn:async()=>await d(r,e,t,{...l,status:"deleted"}),enabled:!!r,staleTime:3e4,placeholderData:a.Wk})}},89348:function(e,t,l){l.d(t,{$:function(){return x}});var s=l(57437),a=l(16312),r=l(42264),i=l(65869),n=l(99397),o=l(2265),d=l(37592),c=l(99981),m=l(49322),u=l(15051),h=l(32489);function g(e){let{group:t,onChange:l,availableModels:a,maxFallbacks:r}=e,i=a.filter(e=>e!==t.primaryModel),n=e=>{let s=t.fallbackModels.filter((t,l)=>l!==e);l({...t,fallbackModels:s})},o=t.fallbackModels.length{let s=[...t.fallbackModels];s.includes(e)&&(s=s.filter(t=>t!==e)),l({...t,primaryModel:e,fallbackModels:s})},showSearch:!0,filterOption:(e,t)=>{var l;return(null!==(l=null==t?void 0:t.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:a.map(e=>({label:e,value:e}))}),!t.primaryModel&&(0,s.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-amber-600 text-xs bg-amber-50 p-2 rounded",children:[(0,s.jsx)(m.Z,{className:"w-4 h-4"}),(0,s.jsx)("span",{children:"Select a model to begin configuring fallbacks"})]})]}),(0,s.jsx)("div",{className:"flex items-center justify-center -my-4 z-10",children:(0,s.jsxs)("div",{className:"bg-indigo-50 text-indigo-500 px-4 py-1 rounded-full text-xs font-bold border border-indigo-100 flex items-center gap-2 shadow-sm",children:[(0,s.jsx)(u.Z,{className:"w-4 h-4"}),"IF FAILS, TRY..."]})}),(0,s.jsxs)("div",{className:"transition-opacity duration-300 ".concat(t.primaryModel?"opacity-100":"opacity-50 pointer-events-none"),children:[(0,s.jsxs)("label",{className:"block text-sm font-semibold text-gray-700 mb-2",children:["Fallback Chain ",(0,s.jsx)("span",{className:"text-red-500",children:"*"}),(0,s.jsxs)("span",{className:"text-xs text-gray-500 font-normal ml-2",children:["(Max ",r," fallbacks at a time)"]})]}),(0,s.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 border border-gray-200",children:[(0,s.jsxs)("div",{className:"mb-4",children:[(0,s.jsx)(d.default,{mode:"multiple",className:"w-full",size:"large",placeholder:o?"Select fallback models to add...":"Maximum ".concat(r," fallbacks reached"),value:t.fallbackModels,onChange:e=>{let s=e.slice(0,r);l({...t,fallbackModels:s})},disabled:!t.primaryModel,options:i.map(e=>({label:e,value:e})),optionRender:(e,l)=>{let a=t.fallbackModels.includes(e.value),r=a?t.fallbackModels.indexOf(e.value)+1:null;return(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[a&&null!==r&&(0,s.jsx)("span",{className:"flex items-center justify-center w-5 h-5 rounded bg-indigo-100 text-indigo-600 text-xs font-bold",children:r}),(0,s.jsx)("span",{children:e.label})]})},maxTagCount:"responsive",maxTagPlaceholder:e=>(0,s.jsx)(c.Z,{styles:{root:{pointerEvents:"none"}},title:e.map(e=>{let{value:t}=e;return t}).join(", "),children:(0,s.jsxs)("span",{children:["+",e.length," more"]})}),showSearch:!0,filterOption:(e,t)=>{var l;return(null!==(l=null==t?void 0:t.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())}}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:o?"Search and select multiple models. Selected models will appear below in order. (".concat(t.fallbackModels.length,"/").concat(r," used)"):"Maximum ".concat(r," fallbacks reached. Remove some to add more.")})]}),(0,s.jsx)("div",{className:"space-y-2 min-h-[100px]",children:0===t.fallbackModels.length?(0,s.jsxs)("div",{className:"h-32 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center text-gray-400",children:[(0,s.jsx)("span",{className:"text-sm",children:"No fallback models selected"}),(0,s.jsx)("span",{className:"text-xs mt-1",children:"Add models from the dropdown above"})]}):t.fallbackModels.map((e,t)=>(0,s.jsxs)("div",{className:"group flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200 hover:border-indigo-300 hover:shadow-sm transition-all",children:[(0,s.jsxs)("div",{className:"flex items-center gap-3",children:[(0,s.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded bg-gray-100 text-gray-400 group-hover:text-indigo-500 group-hover:bg-indigo-50",children:(0,s.jsx)("span",{className:"text-xs font-bold",children:t+1})}),(0,s.jsx)("div",{children:(0,s.jsx)("span",{className:"font-medium text-gray-800",children:e})})]}),(0,s.jsx)("button",{type:"button",onClick:()=>n(t),className:"opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-red-500 p-1",children:(0,s.jsx)(h.Z,{className:"w-4 h-4"})})]},"".concat(e,"-").concat(t)))})]})]})]})}function x(e){let{groups:t,onGroupsChange:l,availableModels:d,maxFallbacks:c=5,maxGroups:m=5}=e,[u,h]=(0,o.useState)(t.length>0?t[0].id:"1");(0,o.useEffect)(()=>{t.length>0?t.some(e=>e.id===u)||h(t[0].id):h("1")},[t]);let x=()=>{if(t.length>=m)return;let e=Date.now().toString();l([...t,{id:e,primaryModel:null,fallbackModels:[]}]),h(e)},p=e=>{if(1===t.length){r.ZP.warning("At least one group is required");return}let s=t.filter(t=>t.id!==e);l(s),u===e&&s.length>0&&h(s[s.length-1].id)},y=e=>{l(t.map(t=>t.id===e.id?e:t))},f=t.map((e,l)=>{let a=e.primaryModel?e.primaryModel:"Group ".concat(l+1);return{key:e.id,label:a,closable:t.length>1,children:(0,s.jsx)(g,{group:e,onChange:y,availableModels:d,maxFallbacks:c})}});return 0===t.length?(0,s.jsxs)("div",{className:"text-center py-12 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[(0,s.jsx)("p",{className:"text-gray-500 mb-4",children:"No fallback groups configured"}),(0,s.jsx)(a.z,{variant:"primary",onClick:x,icon:()=>(0,s.jsx)(n.Z,{className:"w-4 h-4"}),children:"Create First Group"})]}):(0,s.jsx)(i.default,{type:"editable-card",activeKey:u,onChange:h,onEdit:(e,l)=>{"add"===l?x():"remove"===l&&t.length>1&&p(e)},items:f,className:"fallback-tabs",tabBarStyle:{marginBottom:0},hideAdd:t.length>=m})}},62099:function(e,t,l){var s=l(57437),a=l(2265),r=l(37592),i=l(99981),n=l(23496),o=l(63709),d=l(15424),c=l(31283);let{Option:m}=r.default;t.Z=e=>{var t;let{form:l,autoRotationEnabled:u,onAutoRotationChange:h,rotationInterval:g,onRotationIntervalChange:x,isCreateMode:p=!1}=e,y=g&&!["7d","30d","90d","180d","365d"].includes(g),[f,j]=(0,a.useState)(y),[b,_]=(0,a.useState)(y?g:""),[v,N]=(0,a.useState)((null==l?void 0:null===(t=l.getFieldValue)||void 0===t?void 0:t.call(l,"duration"))||"");return(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Key Expiry Settings"}),(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,s.jsx)("span",{children:"Expire Key"}),(0,s.jsx)(i.Z,{title:p?"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Leave empty to never expire.":"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Use -1 to never expire.",children:(0,s.jsx)(d.Z,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,s.jsx)(c.o,{name:"duration",placeholder:p?"e.g., 30d or leave empty to never expire":"e.g., 30d or -1 to never expire",className:"w-full",value:v,onValueChange:e=>{N(e),l&&"function"==typeof l.setFieldValue?l.setFieldValue("duration",e):l&&"function"==typeof l.setFieldsValue&&l.setFieldsValue({duration:e})}})]})]}),(0,s.jsx)(n.Z,{}),(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Auto-Rotation Settings"}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,s.jsx)("span",{children:"Enable Auto-Rotation"}),(0,s.jsx)(i.Z,{title:"Key will automatically regenerate at the specified interval for enhanced security.",children:(0,s.jsx)(d.Z,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,s.jsx)(o.Z,{checked:u,onChange:h,size:"default",className:u?"":"bg-gray-400"})]}),u&&(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,s.jsx)("span",{children:"Rotation Interval"}),(0,s.jsx)(i.Z,{title:"How often the key should be automatically rotated. Choose the interval that best fits your security requirements.",children:(0,s.jsx)(d.Z,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)(r.default,{value:f?"custom":g,onChange:e=>{"custom"===e?j(!0):(j(!1),_(""),x(e))},className:"w-full",placeholder:"Select interval",children:[(0,s.jsx)(m,{value:"7d",children:"7 days"}),(0,s.jsx)(m,{value:"30d",children:"30 days"}),(0,s.jsx)(m,{value:"90d",children:"90 days"}),(0,s.jsx)(m,{value:"180d",children:"180 days"}),(0,s.jsx)(m,{value:"365d",children:"365 days"}),(0,s.jsx)(m,{value:"custom",children:"Custom interval"})]}),f&&(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsx)(c.o,{value:b,onChange:e=>{let t=e.target.value;_(t),x(t)},placeholder:"e.g., 1s, 5m, 2h, 14d"}),(0,s.jsx)("div",{className:"text-xs text-gray-500",children:"Supported formats: seconds (s), minutes (m), hours (h), days (d)"})]})]})]})]}),u&&(0,s.jsx)("div",{className:"bg-blue-50 p-3 rounded-md text-sm text-blue-700",children:"When rotation occurs, you'll receive a notification with the new key. The old key will be deactivated after a brief grace period."})]})]})}},72885:function(e,t,l){var s=l(57437),a=l(2265),r=l(77355),i=l(93416),n=l(74998),o=l(95704),d=l(76593),c=l(9114);t.Z=e=>{let{accessToken:t,initialModelAliases:l={},onAliasUpdate:m,showExampleConfig:u=!0}=e,[h,g]=(0,a.useState)([]),[x,p]=(0,a.useState)({aliasName:"",targetModel:""}),[y,f]=(0,a.useState)(null);(0,a.useEffect)(()=>{g(Object.entries(l).map((e,t)=>{let[l,s]=e;return{id:"".concat(t,"-").concat(l),aliasName:l,targetModel:s}}))},[l]);let j=e=>{f({...e})},b=()=>{if(!y)return;if(!y.aliasName||!y.targetModel){c.ZP.fromBackend("Please provide both alias name and target model");return}if(h.some(e=>e.id!==y.id&&e.aliasName===y.aliasName)){c.ZP.fromBackend("An alias with this name already exists");return}let e=h.map(e=>e.id===y.id?y:e);g(e),f(null);let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),m&&m(t),c.ZP.success("Alias updated successfully")},_=()=>{f(null)},v=e=>{let t=h.filter(t=>t.id!==e);g(t);let l={};t.forEach(e=>{l[e.aliasName]=e.targetModel}),m&&m(l),c.ZP.success("Alias deleted successfully")},N=h.reduce((e,t)=>(e[t.aliasName]=t.targetModel,e),{});return(0,s.jsxs)("div",{className:"mt-4",children:[(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsx)(o.xv,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,s.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,s.jsx)("input",{type:"text",value:x.aliasName,onChange:e=>p({...x,aliasName:e.target.value}),placeholder:"e.g., gpt-4o",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model"}),(0,s.jsx)(d.Z,{accessToken:t,value:x.targetModel,placeholder:"Select target model",onChange:e=>p({...x,targetModel:e}),showLabel:!1})]}),(0,s.jsx)("div",{className:"flex items-end",children:(0,s.jsxs)("button",{onClick:()=>{if(!x.aliasName||!x.targetModel){c.ZP.fromBackend("Please provide both alias name and target model");return}if(h.some(e=>e.aliasName===x.aliasName)){c.ZP.fromBackend("An alias with this name already exists");return}let e=[...h,{id:"".concat(Date.now(),"-").concat(x.aliasName),aliasName:x.aliasName,targetModel:x.targetModel}];g(e),p({aliasName:"",targetModel:""});let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),m&&m(t),c.ZP.success("Alias added successfully")},disabled:!x.aliasName||!x.targetModel,className:"flex items-center px-4 py-2 rounded-md text-sm ".concat(x.aliasName&&x.targetModel?"bg-green-600 text-white hover:bg-green-700":"bg-gray-300 text-gray-500 cursor-not-allowed"),children:[(0,s.jsx)(r.Z,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,s.jsx)(o.xv,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,s.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,s.jsx)("div",{className:"overflow-x-auto",children:(0,s.jsxs)(o.iA,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,s.jsx)(o.ss,{children:(0,s.jsxs)(o.SC,{children:[(0,s.jsx)(o.xs,{className:"py-1 h-8",children:"Alias Name"}),(0,s.jsx)(o.xs,{className:"py-1 h-8",children:"Target Model"}),(0,s.jsx)(o.xs,{className:"py-1 h-8",children:"Actions"})]})}),(0,s.jsxs)(o.RM,{children:[h.map(e=>(0,s.jsx)(o.SC,{className:"h-8",children:y&&y.id===e.id?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o.pj,{className:"py-0.5",children:(0,s.jsx)("input",{type:"text",value:y.aliasName,onChange:e=>f({...y,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,s.jsx)(o.pj,{className:"py-0.5",children:(0,s.jsx)(d.Z,{accessToken:t,value:y.targetModel,onChange:e=>f({...y,targetModel:e}),showLabel:!1,style:{height:"32px"}})}),(0,s.jsx)(o.pj,{className:"py-0.5 whitespace-nowrap",children:(0,s.jsxs)("div",{className:"flex space-x-2",children:[(0,s.jsx)("button",{onClick:b,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,s.jsx)("button",{onClick:_,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o.pj,{className:"py-0.5 text-sm text-gray-900",children:e.aliasName}),(0,s.jsx)(o.pj,{className:"py-0.5 text-sm text-gray-500",children:e.targetModel}),(0,s.jsx)(o.pj,{className:"py-0.5 whitespace-nowrap",children:(0,s.jsxs)("div",{className:"flex space-x-2",children:[(0,s.jsx)("button",{onClick:()=>j(e),className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,s.jsx)(i.Z,{className:"w-3 h-3"})}),(0,s.jsx)("button",{onClick:()=>v(e.id),className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,s.jsx)(n.Z,{className:"w-3 h-3"})})]})})]})},e.id)),0===h.length&&(0,s.jsx)(o.SC,{children:(0,s.jsx)(o.pj,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),u&&(0,s.jsxs)(o.Zb,{children:[(0,s.jsx)(o.Dx,{className:"mb-4",children:"Configuration Example"}),(0,s.jsx)(o.xv,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config:"}),(0,s.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,s.jsxs)("div",{className:"text-gray-700",children:["model_aliases:",0===Object.keys(N).length?(0,s.jsxs)("span",{className:"text-gray-500",children:[(0,s.jsx)("br",{}),"\xa0\xa0# No aliases configured yet"]}):Object.entries(N).map(e=>{let[t,l]=e;return(0,s.jsxs)("span",{children:[(0,s.jsx)("br",{}),'\xa0\xa0"',t,'": "',l,'"']},t)})]})})]})]})}},76593:function(e,t,l){var s=l(57437),a=l(2265),r=l(56522),i=l(37592),n=l(69993),o=l(10703);t.Z=e=>{let{accessToken:t,value:l,placeholder:d="Select a Model",onChange:c,disabled:m=!1,style:u,className:h,showLabel:g=!0,labelText:x="Select Model"}=e,[p,y]=(0,a.useState)(l),[f,j]=(0,a.useState)(!1),[b,_]=(0,a.useState)([]),v=(0,a.useRef)(null);return(0,a.useEffect)(()=>{y(l)},[l]),(0,a.useEffect)(()=>{t&&(async()=>{try{let e=await (0,o.p)(t);console.log("Fetched models for selector:",e),e.length>0&&_(e)}catch(e){console.error("Error fetching model info:",e)}})()},[t]),(0,s.jsxs)("div",{children:[g&&(0,s.jsxs)(r.x,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,s.jsx)(n.Z,{className:"mr-2"})," ",x]}),(0,s.jsx)(i.default,{value:p,placeholder:d,onChange:e=>{"custom"===e?(j(!0),y(void 0)):(j(!1),y(e),c&&c(e))},options:[...Array.from(new Set(b.map(e=>e.model_group))).map((e,t)=>({value:e,label:e,key:t})),{value:"custom",label:"Enter custom model",key:"custom"}],style:{width:"100%",...u},showSearch:!0,className:"rounded-md ".concat(h||""),disabled:m}),f&&(0,s.jsx)(r.o,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{y(e),c&&c(e)},500)},disabled:m})]})}},2597:function(e,t,l){var s=l(57437);l(2265);var a=l(92280),r=l(54507);t.Z=function(e){let{value:t,onChange:l,premiumUser:i=!1,disabledCallbacks:n=[],onDisabledCallbacksChange:o}=e;return i?(0,s.jsx)(r.Z,{value:t,onChange:l,disabledCallbacks:n,onDisabledCallbacksChange:o}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex flex-wrap gap-2 mb-3",children:[(0,s.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-green-50 border border-green-200 text-green-800 text-sm font-medium opacity-50",children:"✨ langfuse-logging"}),(0,s.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-green-50 border border-green-200 text-green-800 text-sm font-medium opacity-50",children:"✨ datadog-logging"})]}),(0,s.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,s.jsxs)(a.x,{className:"text-sm text-yellow-800",children:["Setting Key/Team logging settings is a LiteLLM Enterprise feature. Global Logging Settings are available for all free users. Get a trial key"," ",(0,s.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})}},65895:function(e,t,l){var s=l(57437);l(2265);var a=l(37592),r=l(10032),i=l(99981),n=l(15424);let{Option:o}=a.default;t.Z=e=>{let{type:t,name:l,showDetailedDescriptions:d=!0,className:c="",initialValue:m=null,form:u,onChange:h}=e,g=t.toUpperCase(),x=t.toLowerCase(),p="Select 'guaranteed_throughput' to prevent overallocating ".concat(g," limit when the key belongs to a Team with specific ").concat(g," limits.");return(0,s.jsx)(r.Z.Item,{label:(0,s.jsxs)("span",{children:[g," Rate Limit Type"," ",(0,s.jsx)(i.Z,{title:p,children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:l,initialValue:m,className:c,children:(0,s.jsx)(a.default,{defaultValue:d?"default":void 0,placeholder:"Select rate limit type",style:{width:"100%"},optionLabelProp:d?"label":void 0,onChange:e=>{u&&u.setFieldValue(l,e),h&&h(e)},children:d?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o,{value:"best_effort_throughput",label:"Default",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,s.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Best effort throughput - no error if we're overallocating ",x," (Team/Key Limits checked at runtime)."]})]})}),(0,s.jsx)(o,{value:"guaranteed_throughput",label:"Guaranteed throughput",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Guaranteed throughput"}),(0,s.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Guaranteed throughput - raise an error if we're overallocating ",x," (also checks model-specific limits)"]})]})}),(0,s.jsx)(o,{value:"dynamic",label:"Dynamic",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Dynamic"}),(0,s.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["If the key has a set ",g," (e.g. 2 ",g,") and there are no 429 errors, it can dynamically exceed the limit when the model being called is not erroring."]})]})})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o,{value:"best_effort_throughput",children:"Best effort throughput"}),(0,s.jsx)(o,{value:"guaranteed_throughput",children:"Guaranteed throughput"}),(0,s.jsx)(o,{value:"dynamic",children:"Dynamic"})]})})})}},76364:function(e,t,l){var s=l(57437),a=l(2265),r=l(58643),i=l(19250),n=l(56334),o=l(89348),d=l(10703);let c=(0,a.forwardRef)((e,t)=>{let{accessToken:l,value:c,onChange:m,modelData:u}=e,[h,g]=(0,a.useState)({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),[x,p]=(0,a.useState)([]),[y,f]=(0,a.useState)([]),[j,b]=(0,a.useState)([]),[_,v]=(0,a.useState)([]),[N,w]=(0,a.useState)({}),[k,S]=(0,a.useState)({}),Z=(0,a.useRef)(!1),C=(0,a.useRef)(null),M=e=>e&&0!==e.length?e.map((e,t)=>{let[l,s]=Object.entries(e)[0];return{id:(t+1).toString(),primaryModel:l||null,fallbackModels:s||[]}}):[{id:"1",primaryModel:null,fallbackModels:[]}],P=e=>e.filter(e=>e.primaryModel&&e.fallbackModels.length>0).map(e=>({[e.primaryModel]:e.fallbackModels}));(0,a.useEffect)(()=>{let e=(null==c?void 0:c.router_settings)?JSON.stringify({routing_strategy:c.router_settings.routing_strategy,fallbacks:c.router_settings.fallbacks,enable_tag_filtering:c.router_settings.enable_tag_filtering}):null;if(Z.current&&e===C.current){Z.current=!1;return}if(Z.current&&e!==C.current&&(Z.current=!1),e!==C.current){if(C.current=e,null==c?void 0:c.router_settings){var t;let e=c.router_settings,{fallbacks:l,...s}=e;g({routerSettings:s,selectedStrategy:e.routing_strategy||null,enableTagFiltering:null!==(t=e.enable_tag_filtering)&&void 0!==t&&t});let a=e.fallbacks||[];p(a),f(M(a))}else g({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),p([]),f([{id:"1",primaryModel:null,fallbackModels:[]}])}},[c]),(0,a.useEffect)(()=>{l&&(0,i.getRouterSettingsCall)(l).then(e=>{if(e.fields){let t={};e.fields.forEach(e=>{t[e.field_name]={ui_field_name:e.ui_field_name,field_description:e.field_description,options:e.options,link:e.link}}),w(t);let l=e.fields.find(e=>"routing_strategy"===e.field_name);(null==l?void 0:l.options)&&v(l.options),e.routing_strategy_descriptions&&S(e.routing_strategy_descriptions)}})},[l]),(0,a.useEffect)(()=>{l&&(async()=>{try{let e=await (0,d.p)(l);b(e)}catch(e){console.error("Error fetching model info for fallbacks:",e)}})()},[l]);let T=()=>{let e=new Set(["allowed_fails","cooldown_time","num_retries","timeout","retry_after"]),t=new Set(["model_group_alias","retry_policy"]),l=(l,s,a)=>{if(null==s)return a;let r=String(s).trim();if(""===r||"null"===r.toLowerCase())return null;if(e.has(l)){let e=Number(r);return Number.isNaN(e)?a:e}if(t.has(l)){if(""===r)return null;try{return JSON.parse(r)}catch(e){return a}}return"true"===r.toLowerCase()||"false"!==r.toLowerCase()&&r},s=Object.fromEntries(Object.entries({...h.routerSettings,enable_tag_filtering:h.enableTagFiltering,routing_strategy:h.selectedStrategy,fallbacks:x.length>0?x:null}).map(e=>{let[t,s]=e;if("routing_strategy_args"!==t&&"routing_strategy"!==t&&"enable_tag_filtering"!==t&&"fallbacks"!==t){let e=document.querySelector('input[name="'.concat(t,'"]'));if(e&&void 0!==e.value&&""!==e.value){let a=l(t,e.value,s);return[t,a]}}else if("routing_strategy"===t)return[t,h.selectedStrategy];else if("enable_tag_filtering"===t)return[t,h.enableTagFiltering];else if("fallbacks"===t)return[t,x.length>0?x:null];else if("routing_strategy_args"===t&&"latency-based-routing"===h.selectedStrategy){let e=document.querySelector('input[name="lowest_latency_buffer"]'),t=document.querySelector('input[name="ttl"]'),l={};return(null==e?void 0:e.value)&&(l.lowest_latency_buffer=Number(e.value)),(null==t?void 0:t.value)&&(l.ttl=Number(t.value)),["routing_strategy_args",Object.keys(l).length>0?l:null]}return[t,s]}).filter(e=>null!=e)),a=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return null==e||"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length||t&&("number"!=typeof e||Number.isNaN(e))?null:e};return{routing_strategy:a(s.routing_strategy),allowed_fails:a(s.allowed_fails,!0),cooldown_time:a(s.cooldown_time,!0),num_retries:a(s.num_retries,!0),timeout:a(s.timeout,!0),retry_after:a(s.retry_after,!0),fallbacks:x.length>0?x:null,context_window_fallbacks:a(s.context_window_fallbacks),retry_policy:a(s.retry_policy),model_group_alias:a(s.model_group_alias),enable_tag_filtering:h.enableTagFiltering,routing_strategy_args:a(s.routing_strategy_args)}};(0,a.useEffect)(()=>{if(!m)return;let e=setTimeout(()=>{Z.current=!0,m({router_settings:T()})},100);return()=>clearTimeout(e)},[h,x]);let L=Array.from(new Set(j.map(e=>e.model_group))).sort();return((0,a.useImperativeHandle)(t,()=>({getValue:()=>({router_settings:T()})})),l)?(0,s.jsx)("div",{className:"w-full",children:(0,s.jsxs)(r.v0,{className:"w-full",children:[(0,s.jsxs)(r.td,{variant:"line",defaultValue:"1",className:"px-8 pt-4",children:[(0,s.jsx)(r.OK,{value:"1",children:"Loadbalancing"}),(0,s.jsx)(r.OK,{value:"2",children:"Fallbacks"})]}),(0,s.jsxs)(r.nP,{className:"px-8 py-6",children:[(0,s.jsx)(r.x4,{children:(0,s.jsx)(n.Z,{value:h,onChange:g,routerFieldsMetadata:N,availableRoutingStrategies:_,routingStrategyDescriptions:k})}),(0,s.jsx)(r.x4,{children:(0,s.jsx)(o.$,{groups:y,onGroupsChange:e=>{f(e),p(P(e))},availableModels:L,maxFallbacks:5,maxGroups:5})})]})]})}):null});c.displayName="RouterSettingsAccordion",t.Z=c},71098:function(e,t,l){l.d(t,{ZP:function(){return et},wk:function(){return X},Nr:function(){return ee}});var s=l(57437),a=l(30280),r=l(80443),i=l(59872),n=l(15424),o=l(29827),d=l(87452),c=l(88829),m=l(72208),u=l(78489),h=l(49804),g=l(67101),x=l(84264),p=l(49566),y=l(96761),f=l(37592),j=l(10032),b=l(22116),_=l(99981),v=l(29967),N=l(5545),w=l(63709),k=l(4260),S=l(7310),Z=l.n(S),C=l(2265),M=l(29233),P=l(20347),T=l(82586),L=l(97434),F=l(65925),A=l(63610),E=l(62099),I=l(72885),V=l(95096),R=l(2597),O=l(65895),D=l(76364),K=l(84376),U=l(7765),q=l(46468),B=l(97492),G=l(68473),z=l(9114),J=l(19250),W=l(24199),H=l(97415);let Y=e=>{let t;if(!(t=!e||"object"!=typeof e||e instanceof Error?String(e):JSON.stringify(e)).includes("/key/generate")&&!t.includes("KeyManagementRoutes.KEY_GENERATE"))return"Error creating the key: ".concat(e);let l=t;try{if(!e||"object"!=typeof e||e instanceof Error){let e=t.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]),s=(null==t?void 0:t.error)||t;(null==s?void 0:s.message)&&(l=s.message)}}else{let t=(null==e?void 0:e.error)||e;(null==t?void 0:t.message)&&(l=t.message)}}catch(e){}return t.includes("team_member_permission_error")||l.includes("Team member does not have permissions")?"Team member does not have permission to generate key for this team. Ask your proxy admin to configure the team member permission settings.":"Error creating the key: ".concat(e)},{Option:$}=f.default,Q=e=>{let t=[];if(console.log("data:",JSON.stringify(e)),e)for(let l of e)l.metadata&&l.metadata.tags&&t.push(...l.metadata.tags);let l=Array.from(new Set(t)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",l),l},X=async(e,t,l,s)=>{try{if(null===e||null===t)return[];if(null!==l){let a=(await (0,J.modelAvailableCall)(l,e,t,!0,s,!0)).data.map(e=>e.id);return console.log("available_model_names:",a),a}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},ee=async(e,t,l,s)=>{try{if(null===e||null===t)return;if(null!==l){let a=(await (0,J.modelAvailableCall)(l,e,t)).data.map(e=>e.id);console.log("available_model_names:",a),s(a)}}catch(e){console.error("Error fetching user models:",e)}};var et=e=>{let{team:t,teams:l,data:S,addKey:et}=e,{accessToken:el,userId:es,userRole:ea,premiumUser:er}=(0,r.Z)(),ei=(0,o.NL)(),[en]=j.Z.useForm(),[eo,ed]=(0,C.useState)(!1),[ec,em]=(0,C.useState)(null),[eu,eh]=(0,C.useState)(null),[eg,ex]=(0,C.useState)([]),[ep,ey]=(0,C.useState)([]),[ef,ej]=(0,C.useState)("you"),[eb,e_]=(0,C.useState)(Q(S)),[ev,eN]=(0,C.useState)([]),[ew,ek]=(0,C.useState)([]),[eS,eZ]=(0,C.useState)([]),[eC,eM]=(0,C.useState)([]),[eP,eT]=(0,C.useState)(t),[eL,eF]=(0,C.useState)(!1),[eA,eE]=(0,C.useState)(null),[eI,eV]=(0,C.useState)({}),[eR,eO]=(0,C.useState)([]),[eD,eK]=(0,C.useState)(!1),[eU,eq]=(0,C.useState)([]),[eB,eG]=(0,C.useState)([]),[ez,eJ]=(0,C.useState)("llm_api"),[eW,eH]=(0,C.useState)({}),[eY,e$]=(0,C.useState)(!1),[eQ,eX]=(0,C.useState)("30d"),[e0,e4]=(0,C.useState)(null),[e1,e2]=(0,C.useState)(0),e5=()=>{ed(!1),en.resetFields(),eM([]),eG([]),eJ("llm_api"),eH({}),e$(!1),eX("30d"),e4(null),e2(e=>e+1)},e3=()=>{ed(!1),em(null),eT(null),en.resetFields(),eM([]),eG([]),eJ("llm_api"),eH({}),e$(!1),eX("30d"),e4(null),e2(e=>e+1)};(0,C.useEffect)(()=>{es&&ea&&el&&ee(es,ea,el,ex)},[el,es,ea]),(0,C.useEffect)(()=>{let e=async()=>{try{let e=(await (0,J.getPoliciesList)(el)).policies.map(e=>e.policy_name);ek(e)}catch(e){console.error("Failed to fetch policies:",e)}},t=async()=>{try{let e=await (0,J.getPromptsList)(el);eZ(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}};(async()=>{try{let e=(await (0,J.getGuardrailsList)(el)).guardrails.map(e=>e.guardrail_name);eN(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e(),t()},[el]),(0,C.useEffect)(()=>{(async()=>{try{if(el){let e=sessionStorage.getItem("possibleUserRoles");if(e)eV(JSON.parse(e));else{let e=await (0,J.getPossibleUserRoles)(el);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),eV(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[el]);let e7=ep.includes("no-default-models")&&!eP,e6=async e=>{try{var t,l,s,r,i,n,o;let d;let c=null!==(i=null==e?void 0:e.key_alias)&&void 0!==i?i:"",m=null!==(n=null==e?void 0:e.team_id)&&void 0!==n?n:null;if((null!==(o=null==S?void 0:S.filter(e=>e.team_id===m).map(e=>e.key_alias))&&void 0!==o?o:[]).includes(c))throw Error("Key alias ".concat(c," already exists for team with ID ").concat(m,", please provide another key alias"));z.ZP.info("Making API Call"),ed(!0),"you"===ef&&(e.user_id=es);let u={};try{u=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}if("service_account"===ef&&(u.service_account_id=e.key_alias),eC.length>0&&(u={...u,logging:eC.filter(e=>e.callback_name)}),eB.length>0){let e=(0,L.Z3)(eB);u={...u,litellm_disabled_callbacks:e}}if(eY&&(e.auto_rotate=!0,e.rotation_interval=eQ),e.duration&&""!==e.duration.trim()||(e.duration=null),e.metadata=JSON.stringify(u),e.allowed_vector_store_ids&&e.allowed_vector_store_ids.length>0&&(e.object_permission={vector_stores:e.allowed_vector_store_ids},delete e.allowed_vector_store_ids),e.allowed_mcp_servers_and_groups&&((null===(t=e.allowed_mcp_servers_and_groups.servers)||void 0===t?void 0:t.length)>0||(null===(l=e.allowed_mcp_servers_and_groups.accessGroups)||void 0===l?void 0:l.length)>0)){e.object_permission||(e.object_permission={});let{servers:t,accessGroups:l}=e.allowed_mcp_servers_and_groups;t&&t.length>0&&(e.object_permission.mcp_servers=t),l&&l.length>0&&(e.object_permission.mcp_access_groups=l),delete e.allowed_mcp_servers_and_groups}let h=e.mcp_tool_permissions||{};if(Object.keys(h).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=h),delete e.mcp_tool_permissions,e.allowed_mcp_access_groups&&e.allowed_mcp_access_groups.length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_access_groups=e.allowed_mcp_access_groups,delete e.allowed_mcp_access_groups),e.allowed_agents_and_groups&&((null===(s=e.allowed_agents_and_groups.agents)||void 0===s?void 0:s.length)>0||(null===(r=e.allowed_agents_and_groups.accessGroups)||void 0===r?void 0:r.length)>0)){e.object_permission||(e.object_permission={});let{agents:t,accessGroups:l}=e.allowed_agents_and_groups;t&&t.length>0&&(e.object_permission.agents=t),l&&l.length>0&&(e.object_permission.agent_access_groups=l),delete e.allowed_agents_and_groups}Object.keys(eW).length>0&&(e.aliases=JSON.stringify(eW)),(null==e0?void 0:e0.router_settings)&&Object.values(e0.router_settings).some(e=>null!=e&&""!==e)&&(e.router_settings=e0.router_settings),d="service_account"===ef?await (0,J.keyCreateServiceAccountCall)(el,e):await (0,J.keyCreateCall)(el,es,e),console.log("key create Response:",d),et(d),ei.invalidateQueries({queryKey:a.Km.lists()}),em(d.key),eh(d.soft_budget),z.ZP.success("Virtual Key Created"),en.resetFields(),localStorage.removeItem("userData"+es)}catch(t){console.log("error in create key:",t);let e=Y(t);z.ZP.fromBackend(e)}};(0,C.useEffect)(()=>{if(es&&ea&&el){var e;X(es,ea,el,null!==(e=null==eP?void 0:eP.team_id)&&void 0!==e?e:null).then(e=>{var t;ey(Array.from(new Set([...null!==(t=null==eP?void 0:eP.models)&&void 0!==t?t:[],...e])))})}en.setFieldValue("models",[])},[eP,el,es,ea]);let e9=async e=>{if(!e){eO([]);return}eK(!0);try{let t=new URLSearchParams;if(t.append("user_email",e),null==el)return;let l=(await (0,J.userFilterUICall)(el,t)).map(e=>({label:"".concat(e.user_email," (").concat(e.user_id,")"),value:e.user_id,user:e}));eO(l)}catch(e){console.error("Error fetching users:",e),z.ZP.fromBackend("Failed to search for users")}finally{eK(!1)}},e8=(0,C.useCallback)(Z()(e=>e9(e),300),[el]),te=(e,t)=>{let l=t.user;en.setFieldsValue({user_id:l.user_id})};return(0,s.jsxs)("div",{children:[ea&&P.LQ.includes(ea)&&(0,s.jsx)(u.Z,{className:"mx-auto",onClick:()=>ed(!0),children:"+ Create New Key"}),(0,s.jsx)(b.Z,{open:eo,width:1e3,footer:null,onOk:e5,onCancel:e3,children:(0,s.jsxs)(j.Z,{form:en,onFinish:e6,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsxs)("div",{className:"mb-8",children:[(0,s.jsx)(y.Z,{className:"mb-4",children:"Key Ownership"}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Owned By"," ",(0,s.jsx)(_.Z,{title:"Select who will own this Virtual Key",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,s.jsxs)(v.ZP.Group,{onChange:e=>ej(e.target.value),value:ef,children:[(0,s.jsx)(v.ZP,{value:"you",children:"You"}),(0,s.jsx)(v.ZP,{value:"service_account",children:"Service Account"}),"Admin"===ea&&(0,s.jsx)(v.ZP,{value:"another_user",children:"Another User"})]})}),"another_user"===ef&&(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["User ID"," ",(0,s.jsx)(_.Z,{title:"The user who will own this key and be responsible for its usage",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===ef,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,s.jsx)(f.default,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{e8(e)},onSelect:(e,t)=>te(e,t),options:eR,loading:eD,allowClear:!0,style:{width:"100%"},notFoundContent:eD?"Searching...":"No users found"}),(0,s.jsx)(N.ZP,{onClick:()=>eF(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,s.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Team"," ",(0,s.jsx)(_.Z,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:t?t.team_id:null,className:"mt-4",rules:[{required:"service_account"===ef,message:"Please select a team for the service account"}],help:"service_account"===ef?"required":"",children:(0,s.jsx)(K.Z,{teams:l,onChange:e=>{eT((null==l?void 0:l.find(t=>t.team_id===e))||null)}})})]}),e7&&(0,s.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,s.jsx)(x.Z,{className:"text-blue-800 text-sm",children:"Please select a team to continue configuring your Virtual Key. If you do not see any teams, please contact your Proxy Admin to either provide you with access to models or to add you to a team."})}),!e7&&(0,s.jsxs)("div",{className:"mb-8",children:[(0,s.jsx)(y.Z,{className:"mb-4",children:"Key Details"}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["you"===ef||"another_user"===ef?"Key Name":"Service Account ID"," ",(0,s.jsx)(_.Z,{title:"you"===ef||"another_user"===ef?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:"Please input a ".concat("you"===ef?"key name":"service account ID")}],help:"required",children:(0,s.jsx)(p.Z,{placeholder:""})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(_.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,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"models",rules:"management"===ez||"read_only"===ez?[]:[{required:!0,message:"Please select a model"}],help:"management"===ez||"read_only"===ez?"Models field is disabled for this key type":"required",className:"mt-4",children:(0,s.jsxs)(f.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:"management"===ez||"read_only"===ez,onChange:e=>{e.includes("all-team-models")&&en.setFieldsValue({models:["all-team-models"]})},children:[(0,s.jsx)($,{value:"all-team-models",children:"All Team Models"},"all-team-models"),ep.map(e=>(0,s.jsx)($,{value:e,children:(0,q.W0)(e)},e))]})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Key Type"," ",(0,s.jsx)(_.Z,{title:"Select the type of key to determine what routes and operations this key can access",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"key_type",initialValue:"llm_api",className:"mt-4",children:(0,s.jsxs)(f.default,{defaultValue:"llm_api",placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",onChange:e=>{eJ(e),("management"===e||"read_only"===e)&&en.setFieldsValue({models:[]})},children:[(0,s.jsx)($,{value:"default",label:"Default",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,s.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call LLM API + Management routes"})]})}),(0,s.jsx)($,{value:"llm_api",label:"LLM API",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"LLM API"}),(0,s.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only LLM API routes (chat/completions, embeddings, etc.)"})]})}),(0,s.jsx)($,{value:"management",label:"Management",children:(0,s.jsxs)("div",{style:{padding:"4px 0"},children:[(0,s.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,s.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})})]}),!e7&&(0,s.jsx)("div",{className:"mb-8",children:(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)(y.Z,{className:"m-0",children:"Optional Settings"})}),(0,s.jsxs)(c.Z,{children:[(0,s.jsx)(j.Z.Item,{className:"mt-4",label:(0,s.jsxs)("span",{children:["Max Budget (USD)"," ",(0,s.jsx)(_.Z,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:"Budget cannot exceed team max budget: $".concat((null==t?void 0:t.max_budget)!==null&&(null==t?void 0:t.max_budget)!==void 0?null==t?void 0:t.max_budget:"unlimited"),rules:[{validator:async(e,l)=>{if(l&&t&&null!==t.max_budget&&l>t.max_budget)throw Error("Budget cannot exceed team max budget: $".concat((0,i.pw)(t.max_budget,4)))}}],children:(0,s.jsx)(W.Z,{step:.01,precision:2,width:200})}),(0,s.jsx)(j.Z.Item,{className:"mt-4",label:(0,s.jsxs)("span",{children:["Reset Budget"," ",(0,s.jsx)(_.Z,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:"Team Reset Budget: ".concat((null==t?void 0:t.budget_duration)!==null&&(null==t?void 0:t.budget_duration)!==void 0?null==t?void 0:t.budget_duration:"None"),children:(0,s.jsx)(F.Z,{onChange:e=>en.setFieldValue("budget_duration",e)})}),(0,s.jsx)(j.Z.Item,{className:"mt-4",label:(0,s.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,s.jsx)(_.Z,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:"TPM cannot exceed team TPM limit: ".concat((null==t?void 0:t.tpm_limit)!==null&&(null==t?void 0:t.tpm_limit)!==void 0?null==t?void 0:t.tpm_limit:"unlimited"),rules:[{validator:async(e,l)=>{if(l&&t&&null!==t.tpm_limit&&l>t.tpm_limit)throw Error("TPM limit cannot exceed team TPM limit: ".concat(t.tpm_limit))}}],children:(0,s.jsx)(W.Z,{step:1,width:400})}),(0,s.jsx)(O.Z,{type:"tpm",name:"tpm_limit_type",className:"mt-4",initialValue:null,form:en,showDetailedDescriptions:!0}),(0,s.jsx)(j.Z.Item,{className:"mt-4",label:(0,s.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,s.jsx)(_.Z,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:"RPM cannot exceed team RPM limit: ".concat((null==t?void 0:t.rpm_limit)!==null&&(null==t?void 0:t.rpm_limit)!==void 0?null==t?void 0:t.rpm_limit:"unlimited"),rules:[{validator:async(e,l)=>{if(l&&t&&null!==t.rpm_limit&&l>t.rpm_limit)throw Error("RPM limit cannot exceed team RPM limit: ".concat(t.rpm_limit))}}],children:(0,s.jsx)(W.Z,{step:1,width:400})}),(0,s.jsx)(O.Z,{type:"rpm",name:"rpm_limit_type",className:"mt-4",initialValue:null,form:en,showDetailedDescriptions:!0}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Guardrails"," ",(0,s.jsx)(_.Z,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:er?"Select existing guardrails or enter new ones":"Premium feature - Upgrade to set guardrails by key",children:(0,s.jsx)(f.default,{mode:"tags",style:{width:"100%"},disabled:!er,placeholder:er?"Select or enter guardrails":"Premium feature - Upgrade to set guardrails by key",options:ev.map(e=>({value:e,label:e}))})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,s.jsx)(_.Z,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:er?"Bypass global guardrails for this key":"Premium feature - Upgrade to disable global guardrails by key",children:(0,s.jsx)(w.Z,{disabled:!er,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Policies"," ",(0,s.jsx)(_.Z,{title:"Apply policies to this key to control guardrails and other settings",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-4",help:er?"Select existing policies or enter new ones":"Premium feature - Upgrade to set policies by key",children:(0,s.jsx)(f.default,{mode:"tags",style:{width:"100%"},disabled:!er,placeholder:er?"Select or enter policies":"Premium feature - Upgrade to set policies by key",options:ew.map(e=>({value:e,label:e}))})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Prompts"," ",(0,s.jsx)(_.Z,{title:"Allow this key to use specific prompt templates",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/prompt_management",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"prompts",className:"mt-4",help:er?"Select existing prompts or enter new ones":"Premium feature - Upgrade to set prompts by key",children:(0,s.jsx)(f.default,{mode:"tags",style:{width:"100%"},disabled:!er,placeholder:er?"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:eS.map(e=>({value:e,label:e}))})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Allowed Pass Through Routes"," ",(0,s.jsx)(_.Z,{title:"Allow this key to use specific pass through routes",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})})]}),name:"allowed_passthrough_routes",className:"mt-4",help:er?"Select existing pass through routes or enter new ones":"Premium feature - Upgrade to set pass through routes by key",children:(0,s.jsx)(V.Z,{onChange:e=>en.setFieldValue("allowed_passthrough_routes",e),value:en.getFieldValue("allowed_passthrough_routes"),accessToken:el,placeholder:er?"Select or enter pass through routes":"Premium feature - Upgrade to set pass through routes by key",disabled:!er,teamId:eP?eP.team_id:null})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,s.jsx)(_.Z,{title:"Select which vector stores this key can access. If none selected, the key will have access to all available vector stores",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_vector_store_ids",className:"mt-4",help:"Select vector stores this key can access. Leave empty for access to all vector stores",children:(0,s.jsx)(H.Z,{onChange:e=>en.setFieldValue("allowed_vector_store_ids",e),value:en.getFieldValue("allowed_vector_store_ids"),accessToken:el,placeholder:"Select vector stores (optional)"})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Metadata"," ",(0,s.jsx)(_.Z,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,s.jsx)(k.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Tags"," ",(0,s.jsx)(_.Z,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,s.jsx)(f.default,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:eb})}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"MCP Settings"})}),(0,s.jsxs)(c.Z,{children:[(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,s.jsx)(_.Z,{title:"Select which MCP servers or access groups this key can access",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",help:"Select MCP servers or access groups this key can access",children:(0,s.jsx)(B.Z,{onChange:e=>en.setFieldValue("allowed_mcp_servers_and_groups",e),value:en.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:el,placeholder:"Select MCP servers or access groups (optional)"})}),(0,s.jsx)(j.Z.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,s.jsx)(k.default,{type:"hidden"})}),(0,s.jsx)(j.Z.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.allowed_mcp_servers_and_groups!==t.allowed_mcp_servers_and_groups||e.mcp_tool_permissions!==t.mcp_tool_permissions,children:()=>{var e;return(0,s.jsx)("div",{className:"mt-6",children:(0,s.jsx)(G.Z,{accessToken:el,selectedServers:(null===(e=en.getFieldValue("allowed_mcp_servers_and_groups"))||void 0===e?void 0:e.servers)||[],toolPermissions:en.getFieldValue("mcp_tool_permissions")||{},onChange:e=>en.setFieldsValue({mcp_tool_permissions:e})})})}})]})]}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Agent Settings"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)(j.Z.Item,{label:(0,s.jsxs)("span",{children:["Allowed Agents"," ",(0,s.jsx)(_.Z,{title:"Select which agents or access groups this key can access",children:(0,s.jsx)(n.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",help:"Select agents or access groups this key can access",children:(0,s.jsx)(T.Z,{onChange:e=>en.setFieldValue("allowed_agents_and_groups",e),value:en.getFieldValue("allowed_agents_and_groups"),accessToken:el,placeholder:"Select agents or access groups (optional)"})})})]}),er?(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Logging Settings"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(R.Z,{value:eC,onChange:eM,premiumUser:!0,disabledCallbacks:eB,onDisabledCallbacksChange:eG})})})]}):(0,s.jsx)(_.Z,{title:(0,s.jsxs)("span",{children:["Key-level logging settings is an enterprise feature, get in touch -",(0,s.jsx)("a",{href:"https://www.litellm.ai/enterprise",target:"_blank",children:"https://www.litellm.ai/enterprise"})]}),placement:"top",children:(0,s.jsxs)("div",{style:{position:"relative"},children:[(0,s.jsx)("div",{style:{opacity:.5},children:(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Logging Settings"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(R.Z,{value:eC,onChange:eM,premiumUser:!1,disabledCallbacks:eB,onDisabledCallbacksChange:eG})})})]})}),(0,s.jsx)("div",{style:{position:"absolute",inset:0,cursor:"not-allowed"}})]})}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Router Settings"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)("div",{className:"mt-4 w-full",children:(0,s.jsx)(D.Z,{accessToken:el||"",value:e0||void 0,onChange:e4,modelData:eg.length>0?{data:eg.map(e=>({model_name:e}))}:void 0},e1)})})]},"router-settings-accordion-".concat(e1)),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Model Aliases"})}),(0,s.jsx)(c.Z,{children:(0,s.jsxs)("div",{className:"mt-4",children:[(0,s.jsx)(x.Z,{className:"text-sm text-gray-600 mb-4",children:"Create custom aliases for models that can be used in API calls. This allows you to create shortcuts for specific models."}),(0,s.jsx)(I.Z,{accessToken:el,initialModelAliases:eW,onAliasUpdate:eH,showExampleConfig:!1})]})})]}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsx)("b",{children:"Key Lifecycle"})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(E.Z,{form:en,autoRotationEnabled:eY,onAutoRotationChange:e$,rotationInterval:eQ,onRotationIntervalChange:eX,isCreateMode:!0})})}),(0,s.jsx)(j.Z.Item,{name:"duration",hidden:!0,initialValue:null,children:(0,s.jsx)(k.default,{})})]}),(0,s.jsxs)(d.Z,{className:"mt-4 mb-4",children:[(0,s.jsx)(m.Z,{children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("b",{children:"Advanced Settings"}),(0,s.jsx)(_.Z,{title:(0,s.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,s.jsx)("a",{href:J.proxyBaseUrl?"".concat(J.proxyBaseUrl,"/#/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,s.jsx)(n.Z,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,s.jsx)(c.Z,{children:(0,s.jsx)(A.Z,{schemaComponent:"GenerateKeyRequest",form:en,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(N.ZP,{htmlType:"submit",disabled:e7,style:{opacity:e7?.5:1},children:"Create Key"})})]})}),eL&&(0,s.jsx)(b.Z,{title:"Create New User",open:eL,onCancel:()=>eF(!1),footer:null,width:800,children:(0,s.jsx)(U.Z,{userID:es,accessToken:el,teams:l,possibleUIRoles:eI,onUserCreated:e=>{eE(e),en.setFieldsValue({user_id:e}),eF(!1)},isEmbedded:!0})}),ec&&(0,s.jsx)(b.Z,{open:eo,onOk:e5,onCancel:e3,footer:null,children:(0,s.jsxs)(g.Z,{numItems:1,className:"gap-2 w-full",children:[(0,s.jsx)(y.Z,{children:"Save your Key"}),(0,s.jsx)(h.Z,{numColSpan:1,children:(0,s.jsxs)("p",{children:["Please save this secret key somewhere safe and accessible. For security reasons,"," ",(0,s.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,s.jsx)(h.Z,{numColSpan:1,children:null!=ec?(0,s.jsxs)("div",{children:[(0,s.jsx)(x.Z,{className:"mt-3",children:"Virtual Key:"}),(0,s.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,s.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:ec})}),(0,s.jsx)(M.CopyToClipboard,{text:ec,onCopy:()=>{z.ZP.success("Virtual Key copied to clipboard")},children:(0,s.jsx)(u.Z,{className:"mt-3",children:"Copy Virtual Key"})})]}):(0,s.jsx)(x.Z,{children:"Key being created, this might take 30s"})})]})})]})}},56334:function(e,t,l){l.d(t,{Z:function(){return u}});var s=l(57437);l(2265);var a=l(31283);let r={ttl:3600,lowest_latency_buffer:0};var i=e=>{let{routingStrategyArgs:t}=e,l={ttl:"Sliding window to look back over when calculating the average latency of a deployment. Default - 1 hour (in seconds).",lowest_latency_buffer:"Shuffle between deployments within this % of the lowest latency. Default - 0 (i.e. always pick lowest latency)."};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"max-w-3xl",children:[(0,s.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Latency-Based Configuration"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Fine-tune latency-based routing behavior"})]}),(0,s.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(t||r).map(e=>{let[t,r]=e;return(0,s.jsx)("div",{className:"space-y-2",children:(0,s.jsxs)("label",{className:"block",children:[(0,s.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:t.replace(/_/g," ")}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l[t]||""}),(0,s.jsx)(a.o,{name:t,defaultValue:"object"==typeof r?JSON.stringify(r,null,2):null==r?void 0:r.toString(),className:"font-mono text-sm w-full"})]})},t)})})]}),(0,s.jsx)("div",{className:"border-t border-gray-200"})]})},n=e=>{let{routerSettings:t,routerFieldsMetadata:l}=e;return(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"max-w-3xl",children:[(0,s.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Reliability & Retries"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure retry logic and failure handling"})]}),(0,s.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(t).filter(e=>{let[t,l]=e;return"fallbacks"!=t&&"context_window_fallbacks"!=t&&"routing_strategy_args"!=t&&"routing_strategy"!=t&&"enable_tag_filtering"!=t}).map(e=>{var t,r;let[i,n]=e;return(0,s.jsx)("div",{className:"space-y-2",children:(0,s.jsxs)("label",{className:"block",children:[(0,s.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:(null===(t=l[i])||void 0===t?void 0:t.ui_field_name)||i}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:(null===(r=l[i])||void 0===r?void 0:r.field_description)||""}),(0,s.jsx)(a.o,{name:i,defaultValue:null==n||"null"===n?"":"object"==typeof n?JSON.stringify(n,null,2):(null==n?void 0:n.toString())||"",placeholder:"—",className:"font-mono text-sm w-full"})]})},i)})})]})},o=l(37592),d=e=>{var t,l;let{selectedStrategy:a,availableStrategies:r,routingStrategyDescriptions:i,routerFieldsMetadata:n,onStrategyChange:d}=e;return(0,s.jsxs)("div",{className:"space-y-2 max-w-3xl",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:(null===(t=n.routing_strategy)||void 0===t?void 0:t.ui_field_name)||"Routing Strategy"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:(null===(l=n.routing_strategy)||void 0===l?void 0:l.field_description)||""})]}),(0,s.jsx)("div",{className:"routing-strategy-select max-w-3xl",children:(0,s.jsx)(o.default,{value:a,onChange:d,style:{width:"100%"},size:"large",children:r.map(e=>(0,s.jsx)(o.default.Option,{value:e,label:e,children:(0,s.jsxs)("div",{className:"flex flex-col gap-0.5 py-1",children:[(0,s.jsx)("span",{className:"font-mono text-sm font-medium",children:e}),i[e]&&(0,s.jsx)("span",{className:"text-xs text-gray-500 font-normal",children:i[e]})]})},e))})})]})},c=l(59341),m=e=>{var t,l,a;let{enabled:r,routerFieldsMetadata:i,onToggle:n}=e;return(0,s.jsx)("div",{className:"space-y-3 max-w-3xl",children:(0,s.jsxs)("div",{className:"flex items-start justify-between",children:[(0,s.jsxs)("div",{className:"flex-1",children:[(0,s.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:(null===(t=i.enable_tag_filtering)||void 0===t?void 0:t.ui_field_name)||"Enable Tag Filtering"}),(0,s.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:[(null===(l=i.enable_tag_filtering)||void 0===l?void 0:l.field_description)||"",(null===(a=i.enable_tag_filtering)||void 0===a?void 0:a.link)&&(0,s.jsxs)(s.Fragment,{children:[" ",(0,s.jsx)("a",{href:i.enable_tag_filtering.link,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"Learn more"})]})]})]}),(0,s.jsx)(c.Z,{checked:r,onChange:n,className:"ml-4"})]})})},u=e=>{let{value:t,onChange:l,routerFieldsMetadata:a,availableRoutingStrategies:r,routingStrategyDescriptions:o}=e;return(0,s.jsxs)("div",{className:"w-full space-y-8 py-2",children:[(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"max-w-3xl",children:[(0,s.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Routing Settings"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure how requests are routed to deployments"})]}),r.length>0&&(0,s.jsx)(d,{selectedStrategy:t.selectedStrategy||t.routerSettings.routing_strategy||null,availableStrategies:r,routingStrategyDescriptions:o,routerFieldsMetadata:a,onStrategyChange:e=>{l({...t,selectedStrategy:e})}}),(0,s.jsx)(m,{enabled:t.enableTagFiltering,routerFieldsMetadata:a,onToggle:e=>{l({...t,enableTagFiltering:e})}})]}),(0,s.jsx)("div",{className:"border-t border-gray-200"}),"latency-based-routing"===t.selectedStrategy&&(0,s.jsx)(i,{routingStrategyArgs:t.routerSettings.routing_strategy_args}),(0,s.jsx)(n,{routerSettings:t.routerSettings,routerFieldsMetadata:a})]})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1108-051a6fa80f898243.js b/litellm/proxy/_experimental/out/_next/static/chunks/1108-051a6fa80f898243.js new file mode 100644 index 00000000000..a71709bb8a8 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1108-051a6fa80f898243.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1108],{40278:function(t,e,r){"use strict";r.d(e,{Z:function(){return S}});var n=r(5853),o=r(7084),i=r(26898),a=r(13241),u=r(1153),c=r(2265),l=r(47625),s=r(93765),f=r(31699),p=r(97059),h=r(62994),d=r(25311),y=(0,s.z)({chartName:"BarChart",GraphicalChild:f.$,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:p.K},{axisType:"yAxis",AxisComp:h.B}],formatAxisMap:d.t9}),v=r(56940),m=r(26680),b=r(8147),g=r(22190),x=r(65278),w=r(98593),O=r(92666),j=r(32644);let S=c.forwardRef((t,e)=>{let{data:r=[],categories:s=[],index:d,colors:S=i.s,valueFormatter:P=u.Cj,layout:E="horizontal",stack:k=!1,relative:A=!1,startEndOnly:M=!1,animationDuration:_=900,showAnimation:T=!1,showXAxis:C=!0,showYAxis:N=!0,yAxisWidth:D=56,intervalType:I="equidistantPreserveStart",showTooltip:L=!0,showLegend:B=!0,showGridLines:R=!0,autoMinValue:z=!1,minValue:U,maxValue:F,allowDecimals:$=!0,noDataText:q,onValueChange:Z,enableLegendSlider:W=!1,customTooltip:Y,rotateLabelX:H,barCategoryGap:X,tickGap:G=5,xAxisLabel:V,yAxisLabel:K,className:Q,padding:J=C||N?{left:20,right:20}:{left:0,right:0}}=t,tt=(0,n._T)(t,["data","categories","index","colors","valueFormatter","layout","stack","relative","startEndOnly","animationDuration","showAnimation","showXAxis","showYAxis","yAxisWidth","intervalType","showTooltip","showLegend","showGridLines","autoMinValue","minValue","maxValue","allowDecimals","noDataText","onValueChange","enableLegendSlider","customTooltip","rotateLabelX","barCategoryGap","tickGap","xAxisLabel","yAxisLabel","className","padding"]),[te,tr]=(0,c.useState)(60),tn=(0,j.me)(s,S),[to,ti]=c.useState(void 0),[ta,tu]=(0,c.useState)(void 0),tc=!!Z;function tl(t,e,r){var n,o,i,a;r.stopPropagation(),Z&&((0,j.vZ)(to,Object.assign(Object.assign({},t.payload),{value:t.value}))?(tu(void 0),ti(void 0),null==Z||Z(null)):(tu(null===(o=null===(n=t.tooltipPayload)||void 0===n?void 0:n[0])||void 0===o?void 0:o.dataKey),ti(Object.assign(Object.assign({},t.payload),{value:t.value})),null==Z||Z(Object.assign({eventType:"bar",categoryClicked:null===(a=null===(i=t.tooltipPayload)||void 0===i?void 0:i[0])||void 0===a?void 0:a.dataKey},t.payload))))}let ts=(0,j.i4)(z,U,F);return c.createElement("div",Object.assign({ref:e,className:(0,a.q)("w-full h-80",Q)},tt),c.createElement(l.h,{className:"h-full w-full"},(null==r?void 0:r.length)?c.createElement(y,{barCategoryGap:X,data:r,stackOffset:k?"sign":A?"expand":"none",layout:"vertical"===E?"vertical":"horizontal",onClick:tc&&(ta||to)?()=>{ti(void 0),tu(void 0),null==Z||Z(null)}:void 0,margin:{bottom:V?30:void 0,left:K?20:void 0,right:K?5:void 0,top:5}},R?c.createElement(v.q,{className:(0,a.q)("stroke-1","stroke-tremor-border","dark:stroke-dark-tremor-border"),horizontal:"vertical"!==E,vertical:"vertical"===E}):null,"vertical"!==E?c.createElement(p.K,{padding:J,hide:!C,dataKey:d,interval:M?"preserveStartEnd":I,tick:{transform:"translate(0, 6)"},ticks:M?[r[0][d],r[r.length-1][d]]:void 0,fill:"",stroke:"",className:(0,a.q)("mt-4 text-tremor-label","fill-tremor-content","dark:fill-dark-tremor-content"),tickLine:!1,axisLine:!1,angle:null==H?void 0:H.angle,dy:null==H?void 0:H.verticalShift,height:null==H?void 0:H.xAxisHeight,minTickGap:G},V&&c.createElement(m._,{position:"insideBottom",offset:-20,className:"fill-tremor-content-emphasis text-tremor-default font-medium dark:fill-dark-tremor-content-emphasis"},V)):c.createElement(p.K,{hide:!C,type:"number",tick:{transform:"translate(-3, 0)"},domain:ts,fill:"",stroke:"",className:(0,a.q)("text-tremor-label","fill-tremor-content","dark:fill-dark-tremor-content"),tickLine:!1,axisLine:!1,tickFormatter:P,minTickGap:G,allowDecimals:$,angle:null==H?void 0:H.angle,dy:null==H?void 0:H.verticalShift,height:null==H?void 0:H.xAxisHeight},V&&c.createElement(m._,{position:"insideBottom",offset:-20,className:"fill-tremor-content-emphasis text-tremor-default font-medium dark:fill-dark-tremor-content-emphasis"},V)),"vertical"!==E?c.createElement(h.B,{width:D,hide:!N,axisLine:!1,tickLine:!1,type:"number",domain:ts,tick:{transform:"translate(-3, 0)"},fill:"",stroke:"",className:(0,a.q)("text-tremor-label","fill-tremor-content","dark:fill-dark-tremor-content"),tickFormatter:A?t=>"".concat((100*t).toString()," %"):P,allowDecimals:$},K&&c.createElement(m._,{position:"insideLeft",style:{textAnchor:"middle"},angle:-90,offset:-15,className:"fill-tremor-content-emphasis text-tremor-default font-medium dark:fill-dark-tremor-content-emphasis"},K)):c.createElement(h.B,{width:D,hide:!N,dataKey:d,axisLine:!1,tickLine:!1,ticks:M?[r[0][d],r[r.length-1][d]]:void 0,type:"category",interval:"preserveStartEnd",tick:{transform:"translate(0, 6)"},fill:"",stroke:"",className:(0,a.q)("text-tremor-label","fill-tremor-content","dark:fill-dark-tremor-content")},K&&c.createElement(m._,{position:"insideLeft",style:{textAnchor:"middle"},angle:-90,offset:-15,className:"fill-tremor-content-emphasis text-tremor-default font-medium dark:fill-dark-tremor-content-emphasis"},K)),c.createElement(b.u,{wrapperStyle:{outline:"none"},isAnimationActive:!1,cursor:{fill:"#d1d5db",opacity:"0.15"},content:L?t=>{let{active:e,payload:r,label:n}=t;return Y?c.createElement(Y,{payload:null==r?void 0:r.map(t=>{var e;return Object.assign(Object.assign({},t),{color:null!==(e=tn.get(t.dataKey))&&void 0!==e?e:o.fr.Gray})}),active:e,label:n}):c.createElement(w.ZP,{active:e,payload:r,label:n,valueFormatter:P,categoryColors:tn})}:c.createElement(c.Fragment,null),position:{y:0}}),B?c.createElement(g.D,{verticalAlign:"top",height:te,content:t=>{let{payload:e}=t;return(0,x.Z)({payload:e},tn,tr,ta,tc?t=>{tc&&(t!==ta||to?(tu(t),null==Z||Z({eventType:"category",categoryClicked:t})):(tu(void 0),null==Z||Z(null)),ti(void 0))}:void 0,W)}}):null,s.map(t=>{var e;return c.createElement(f.$,{className:(0,a.q)((0,u.bM)(null!==(e=tn.get(t))&&void 0!==e?e:o.fr.Gray,i.K.background).fillColor,Z?"cursor-pointer":""),key:t,name:t,type:"linear",stackId:k||A?"a":void 0,dataKey:t,fill:"",isAnimationActive:T,animationDuration:_,shape:t=>((t,e,r,n)=>{let{fillOpacity:o,name:i,payload:a,value:u}=t,{x:l,width:s,y:f,height:p}=t;return"horizontal"===n&&p<0?(f+=p,p=Math.abs(p)):"vertical"===n&&s<0&&(l+=s,s=Math.abs(s)),c.createElement("rect",{x:l,y:f,width:s,height:p,opacity:e||r&&r!==i?(0,j.vZ)(e,Object.assign(Object.assign({},a),{value:u}))?o:.3:o})})(t,to,ta,E),onClick:tl})})):c.createElement(O.Z,{noDataText:q})))});S.displayName="BarChart"},65278:function(t,e,r){"use strict";r.d(e,{Z:function(){return y}});var n=r(2265);let o=t=>{n.useEffect(()=>{let e=()=>{t()};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[t])};var i=r(5853),a=r(26898),u=r(13241),c=r(1153);let l=t=>{var e=(0,i._T)(t,[]);return n.createElement("svg",Object.assign({},e,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),n.createElement("path",{d:"M8 12L14 6V18L8 12Z"}))},s=t=>{var e=(0,i._T)(t,[]);return n.createElement("svg",Object.assign({},e,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),n.createElement("path",{d:"M16 12L10 18V6L16 12Z"}))},f=(0,c.fn)("Legend"),p=t=>{let{name:e,color:r,onClick:o,activeLegend:i}=t,l=!!o;return n.createElement("li",{className:(0,u.q)(f("legendItem"),"group inline-flex items-center px-2 py-0.5 rounded-tremor-small transition whitespace-nowrap",l?"cursor-pointer":"cursor-default","text-tremor-content",l?"hover:bg-tremor-background-subtle":"","dark:text-dark-tremor-content",l?"dark:hover:bg-dark-tremor-background-subtle":""),onClick:t=>{t.stopPropagation(),null==o||o(e,r)}},n.createElement("svg",{className:(0,u.q)("flex-none h-2 w-2 mr-1.5",(0,c.bM)(r,a.K.text).textColor,i&&i!==e?"opacity-40":"opacity-100"),fill:"currentColor",viewBox:"0 0 8 8"},n.createElement("circle",{cx:4,cy:4,r:4})),n.createElement("p",{className:(0,u.q)("whitespace-nowrap truncate text-tremor-default","text-tremor-content",l?"group-hover:text-tremor-content-emphasis":"","dark:text-dark-tremor-content",i&&i!==e?"opacity-40":"opacity-100",l?"dark:group-hover:text-dark-tremor-content-emphasis":"")},e))},h=t=>{let{icon:e,onClick:r,disabled:o}=t,[i,a]=n.useState(!1),c=n.useRef(null);return n.useEffect(()=>(i?c.current=setInterval(()=>{null==r||r()},300):clearInterval(c.current),()=>clearInterval(c.current)),[i,r]),(0,n.useEffect)(()=>{o&&(clearInterval(c.current),a(!1))},[o]),n.createElement("button",{type:"button",className:(0,u.q)(f("legendSliderButton"),"w-5 group inline-flex items-center truncate rounded-tremor-small transition",o?"cursor-not-allowed":"cursor-pointer",o?"text-tremor-content-subtle":"text-tremor-content hover:text-tremor-content-emphasis hover:bg-tremor-background-subtle",o?"dark:text-dark-tremor-subtle":"dark:text-dark-tremor dark:hover:text-tremor-content-emphasis dark:hover:bg-dark-tremor-background-subtle"),disabled:o,onClick:t=>{t.stopPropagation(),null==r||r()},onMouseDown:t=>{t.stopPropagation(),a(!0)},onMouseUp:t=>{t.stopPropagation(),a(!1)}},n.createElement(e,{className:"w-full"}))},d=n.forwardRef((t,e)=>{let{categories:r,colors:o=a.s,className:c,onClickLegendItem:d,activeLegend:y,enableLegendSlider:v=!1}=t,m=(0,i._T)(t,["categories","colors","className","onClickLegendItem","activeLegend","enableLegendSlider"]),b=n.useRef(null),g=n.useRef(null),[x,w]=n.useState(null),[O,j]=n.useState(null),S=n.useRef(null),P=(0,n.useCallback)(()=>{let t=null==b?void 0:b.current;t&&w({left:t.scrollLeft>0,right:t.scrollWidth-t.clientWidth>t.scrollLeft})},[w]),E=(0,n.useCallback)(t=>{var e,r;let n=null==b?void 0:b.current,o=null==g?void 0:g.current,i=null!==(e=null==n?void 0:n.clientWidth)&&void 0!==e?e:0,a=null!==(r=null==o?void 0:o.clientWidth)&&void 0!==r?r:0;n&&v&&(n.scrollTo({left:"left"===t?n.scrollLeft-i+a:n.scrollLeft+i-a,behavior:"smooth"}),setTimeout(()=>{P()},400))},[v,P]);n.useEffect(()=>{let t=t=>{"ArrowLeft"===t?E("left"):"ArrowRight"===t&&E("right")};return O?(t(O),S.current=setInterval(()=>{t(O)},300)):clearInterval(S.current),()=>clearInterval(S.current)},[O,E]);let k=t=>{t.stopPropagation(),"ArrowLeft"!==t.key&&"ArrowRight"!==t.key||(t.preventDefault(),j(t.key))},A=t=>{t.stopPropagation(),j(null)};return n.useEffect(()=>{let t=null==b?void 0:b.current;return v&&(P(),null==t||t.addEventListener("keydown",k),null==t||t.addEventListener("keyup",A)),()=>{null==t||t.removeEventListener("keydown",k),null==t||t.removeEventListener("keyup",A)}},[P,v]),n.createElement("ol",Object.assign({ref:e,className:(0,u.q)(f("root"),"relative overflow-hidden",c)},m),n.createElement("div",{ref:b,tabIndex:0,className:(0,u.q)("h-full flex",v?(null==x?void 0:x.right)||(null==x?void 0:x.left)?"pl-4 pr-12 items-center overflow-auto snap-mandatory [&::-webkit-scrollbar]:hidden [scrollbar-width:none]":"":"flex-wrap")},r.map((t,e)=>n.createElement(p,{key:"item-".concat(e),name:t,color:o[e%o.length],onClick:d,activeLegend:y}))),v&&((null==x?void 0:x.right)||(null==x?void 0:x.left))?n.createElement(n.Fragment,null,n.createElement("div",{className:(0,u.q)("bg-tremor-background","dark:bg-dark-tremor-background","absolute flex top-0 pr-1 bottom-0 right-0 items-center justify-center h-full"),ref:g},n.createElement(h,{icon:l,onClick:()=>{j(null),E("left")},disabled:!(null==x?void 0:x.left)}),n.createElement(h,{icon:s,onClick:()=>{j(null),E("right")},disabled:!(null==x?void 0:x.right)}))):null)});d.displayName="Legend";let y=(t,e,r,i,a,u)=>{let{payload:c}=t,l=(0,n.useRef)(null);o(()=>{var t,e;r((e=null===(t=l.current)||void 0===t?void 0:t.clientHeight)?Number(e)+20:60)});let s=c.filter(t=>"none"!==t.type);return n.createElement("div",{ref:l,className:"flex items-center justify-end"},n.createElement(d,{categories:s.map(t=>t.value),colors:s.map(t=>e.get(t.value)),onClickLegendItem:a,activeLegend:i,enableLegendSlider:u}))}},98593:function(t,e,r){"use strict";r.d(e,{$B:function(){return c},ZP:function(){return s},zX:function(){return l}});var n=r(2265),o=r(7084),i=r(26898),a=r(13241),u=r(1153);let c=t=>{let{children:e}=t;return n.createElement("div",{className:(0,a.q)("rounded-tremor-default text-tremor-default border","bg-tremor-background shadow-tremor-dropdown border-tremor-border","dark:bg-dark-tremor-background dark:shadow-dark-tremor-dropdown dark:border-dark-tremor-border")},e)},l=t=>{let{value:e,name:r,color:o}=t;return n.createElement("div",{className:"flex items-center justify-between space-x-8"},n.createElement("div",{className:"flex items-center space-x-2"},n.createElement("span",{className:(0,a.q)("shrink-0 rounded-tremor-full border-2 h-3 w-3","border-tremor-background shadow-tremor-card","dark:border-dark-tremor-background dark:shadow-dark-tremor-card",(0,u.bM)(o,i.K.background).bgColor)}),n.createElement("p",{className:(0,a.q)("text-right whitespace-nowrap","text-tremor-content","dark:text-dark-tremor-content")},r)),n.createElement("p",{className:(0,a.q)("font-medium tabular-nums text-right whitespace-nowrap","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis")},e))},s=t=>{let{active:e,payload:r,label:i,categoryColors:u,valueFormatter:s}=t;if(e&&r){let t=r.filter(t=>"none"!==t.type);return n.createElement(c,null,n.createElement("div",{className:(0,a.q)("border-tremor-border border-b px-4 py-2","dark:border-dark-tremor-border")},n.createElement("p",{className:(0,a.q)("font-medium","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis")},i)),n.createElement("div",{className:(0,a.q)("px-4 py-2 space-y-1")},t.map((t,e)=>{var r;let{value:i,name:a}=t;return n.createElement(l,{key:"id-".concat(e),value:s(i),name:a,color:null!==(r=u.get(a))&&void 0!==r?r:o.fr.Blue})})))}return null}},92666:function(t,e,r){"use strict";r.d(e,{Z:function(){return i}});var n=r(13241),o=r(2265);let i=t=>{let{className:e,noDataText:r="No data"}=t;return o.createElement("div",{className:(0,n.q)("flex items-center justify-center w-full h-full border border-dashed rounded-tremor-default","border-tremor-border","dark:border-dark-tremor-border",e)},o.createElement("p",{className:(0,n.q)("text-tremor-content text-tremor-default","dark:text-dark-tremor-content")},r))}},32644:function(t,e,r){"use strict";r.d(e,{FB:function(){return i},i4:function(){return o},me:function(){return n},vZ:function(){return function t(e,r){if(e===r)return!0;if("object"!=typeof e||"object"!=typeof r||null===e||null===r)return!1;let n=Object.keys(e),o=Object.keys(r);if(n.length!==o.length)return!1;for(let i of n)if(!o.includes(i)||!t(e[i],r[i]))return!1;return!0}}});let n=(t,e)=>{let r=new Map;return t.forEach((t,n)=>{r.set(t,e[n%e.length])}),r},o=(t,e,r)=>[t?"auto":null!=e?e:0,null!=r?r:"auto"];function i(t,e){let r=[];for(let n of t)if(Object.prototype.hasOwnProperty.call(n,e)&&(r.push(n[e]),r.length>1))return!1;return!0}},49804:function(t,e,r){"use strict";r.d(e,{Z:function(){return l}});var n=r(5853),o=r(13241),i=r(1153),a=r(2265),u=r(9496);let c=(0,i.fn)("Col"),l=a.forwardRef((t,e)=>{let{numColSpan:r=1,numColSpanSm:i,numColSpanMd:l,numColSpanLg:s,children:f,className:p}=t,h=(0,n._T)(t,["numColSpan","numColSpanSm","numColSpanMd","numColSpanLg","children","className"]),d=(t,e)=>t&&Object.keys(e).includes(String(t))?e[t]:"";return a.createElement("div",Object.assign({ref:e,className:(0,o.q)(c("root"),(()=>{let t=d(r,u.PT),e=d(i,u.SP),n=d(l,u.VS),a=d(s,u._w);return(0,o.q)(t,e,n,a)})(),p)},h),f)});l.displayName="Col"},97765:function(t,e,r){"use strict";r.d(e,{Z:function(){return c}});var n=r(5853),o=r(26898),i=r(13241),a=r(1153),u=r(2265);let c=u.forwardRef((t,e)=>{let{color:r,children:c,className:l}=t,s=(0,n._T)(t,["color","children","className"]);return u.createElement("p",Object.assign({ref:e,className:(0,i.q)(r?(0,a.bM)(r,o.K.lightText).textColor:"text-tremor-content-emphasis dark:text-dark-tremor-content-emphasis",l)},s),c)});c.displayName="Subtitle"},61134:function(t,e,r){var n;!function(o){"use strict";var i,a={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},u=!0,c="[DecimalError] ",l=c+"Invalid argument: ",s=c+"Exponent out of range: ",f=Math.floor,p=Math.pow,h=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,d=f(1286742750677284.5),y={};function v(t,e){var r,n,o,i,a,c,l,s,f=t.constructor,p=f.precision;if(!t.s||!e.s)return e.s||(e=new f(t)),u?E(e,p):e;if(l=t.d,s=e.d,a=t.e,o=e.e,l=l.slice(),i=a-o){for(i<0?(n=l,i=-i,c=s.length):(n=s,o=a,c=l.length),i>(c=(a=Math.ceil(p/7))>c?a+1:c+1)&&(i=c,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for((c=l.length)-(i=s.length)<0&&(i=c,n=s,s=l,l=n),r=0;i;)r=(l[--i]=l[i]+s[i]+r)/1e7|0,l[i]%=1e7;for(r&&(l.unshift(r),++o),c=l.length;0==l[--c];)l.pop();return e.d=l,e.e=o,u?E(e,p):e}function m(t,e,r){if(t!==~~t||tr)throw Error(l+t)}function b(t){var e,r,n,o=t.length-1,i="",a=t[0];if(o>0){for(i+=a,e=1;et.e^this.s<0?1:-1;for(e=0,r=(n=this.d.length)<(o=t.d.length)?n:o;et.d[e]^this.s<0?1:-1;return n===o?0:n>o^this.s<0?1:-1},y.decimalPlaces=y.dp=function(){var t=this.d.length-1,e=(t-this.e)*7;if(t=this.d[t])for(;t%10==0;t/=10)e--;return e<0?0:e},y.dividedBy=y.div=function(t){return g(this,new this.constructor(t))},y.dividedToIntegerBy=y.idiv=function(t){var e=this.constructor;return E(g(this,new e(t),0,1),e.precision)},y.equals=y.eq=function(t){return!this.cmp(t)},y.exponent=function(){return w(this)},y.greaterThan=y.gt=function(t){return this.cmp(t)>0},y.greaterThanOrEqualTo=y.gte=function(t){return this.cmp(t)>=0},y.isInteger=y.isint=function(){return this.e>this.d.length-2},y.isNegative=y.isneg=function(){return this.s<0},y.isPositive=y.ispos=function(){return this.s>0},y.isZero=function(){return 0===this.s},y.lessThan=y.lt=function(t){return 0>this.cmp(t)},y.lessThanOrEqualTo=y.lte=function(t){return 1>this.cmp(t)},y.logarithm=y.log=function(t){var e,r=this.constructor,n=r.precision,o=n+5;if(void 0===t)t=new r(10);else if((t=new r(t)).s<1||t.eq(i))throw Error(c+"NaN");if(this.s<1)throw Error(c+(this.s?"NaN":"-Infinity"));return this.eq(i)?new r(0):(u=!1,e=g(S(this,o),S(t,o),o),u=!0,E(e,n))},y.minus=y.sub=function(t){return t=new this.constructor(t),this.s==t.s?k(this,t):v(this,(t.s=-t.s,t))},y.modulo=y.mod=function(t){var e,r=this.constructor,n=r.precision;if(!(t=new r(t)).s)throw Error(c+"NaN");return this.s?(u=!1,e=g(this,t,0,1).times(t),u=!0,this.minus(e)):E(new r(this),n)},y.naturalExponential=y.exp=function(){return x(this)},y.naturalLogarithm=y.ln=function(){return S(this)},y.negated=y.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t},y.plus=y.add=function(t){return t=new this.constructor(t),this.s==t.s?v(this,t):k(this,(t.s=-t.s,t))},y.precision=y.sd=function(t){var e,r,n;if(void 0!==t&&!!t!==t&&1!==t&&0!==t)throw Error(l+t);if(e=w(this)+1,r=7*(n=this.d.length-1)+1,n=this.d[n]){for(;n%10==0;n/=10)r--;for(n=this.d[0];n>=10;n/=10)r++}return t&&e>r?e:r},y.squareRoot=y.sqrt=function(){var t,e,r,n,o,i,a,l=this.constructor;if(this.s<1){if(!this.s)return new l(0);throw Error(c+"NaN")}for(t=w(this),u=!1,0==(o=Math.sqrt(+this))||o==1/0?(((e=b(this.d)).length+t)%2==0&&(e+="0"),o=Math.sqrt(e),t=f((t+1)/2)-(t<0||t%2),n=new l(e=o==1/0?"5e"+t:(e=o.toExponential()).slice(0,e.indexOf("e")+1)+t)):n=new l(o.toString()),o=a=(r=l.precision)+3;;)if(n=(i=n).plus(g(this,i,a+2)).times(.5),b(i.d).slice(0,a)===(e=b(n.d)).slice(0,a)){if(e=e.slice(a-3,a+1),o==a&&"4999"==e){if(E(i,r+1,0),i.times(i).eq(this)){n=i;break}}else if("9999"!=e)break;a+=4}return u=!0,E(n,r)},y.times=y.mul=function(t){var e,r,n,o,i,a,c,l,s,f=this.constructor,p=this.d,h=(t=new f(t)).d;if(!this.s||!t.s)return new f(0);for(t.s*=this.s,r=this.e+t.e,(l=p.length)<(s=h.length)&&(i=p,p=h,h=i,a=l,l=s,s=a),i=[],n=a=l+s;n--;)i.push(0);for(n=s;--n>=0;){for(e=0,o=l+n;o>n;)c=i[o]+h[n]*p[o-n-1]+e,i[o--]=c%1e7|0,e=c/1e7|0;i[o]=(i[o]+e)%1e7|0}for(;!i[--a];)i.pop();return e?++r:i.shift(),t.d=i,t.e=r,u?E(t,f.precision):t},y.toDecimalPlaces=y.todp=function(t,e){var r=this,n=r.constructor;return(r=new n(r),void 0===t)?r:(m(t,0,1e9),void 0===e?e=n.rounding:m(e,0,8),E(r,t+w(r)+1,e))},y.toExponential=function(t,e){var r,n=this,o=n.constructor;return void 0===t?r=A(n,!0):(m(t,0,1e9),void 0===e?e=o.rounding:m(e,0,8),r=A(n=E(new o(n),t+1,e),!0,t+1)),r},y.toFixed=function(t,e){var r,n,o=this.constructor;return void 0===t?A(this):(m(t,0,1e9),void 0===e?e=o.rounding:m(e,0,8),r=A((n=E(new o(this),t+w(this)+1,e)).abs(),!1,t+w(n)+1),this.isneg()&&!this.isZero()?"-"+r:r)},y.toInteger=y.toint=function(){var t=this.constructor;return E(new t(this),w(this)+1,t.rounding)},y.toNumber=function(){return+this},y.toPower=y.pow=function(t){var e,r,n,o,a,l,s=this,p=s.constructor,h=+(t=new p(t));if(!t.s)return new p(i);if(!(s=new p(s)).s){if(t.s<1)throw Error(c+"Infinity");return s}if(s.eq(i))return s;if(n=p.precision,t.eq(i))return E(s,n);if(l=(e=t.e)>=(r=t.d.length-1),a=s.s,l){if((r=h<0?-h:h)<=9007199254740991){for(o=new p(i),e=Math.ceil(n/7+4),u=!1;r%2&&M((o=o.times(s)).d,e),0!==(r=f(r/2));)M((s=s.times(s)).d,e);return u=!0,t.s<0?new p(i).div(o):E(o,n)}}else if(a<0)throw Error(c+"NaN");return a=a<0&&1&t.d[Math.max(e,r)]?-1:1,s.s=1,u=!1,o=t.times(S(s,n+12)),u=!0,(o=x(o)).s=a,o},y.toPrecision=function(t,e){var r,n,o=this,i=o.constructor;return void 0===t?(r=w(o),n=A(o,r<=i.toExpNeg||r>=i.toExpPos)):(m(t,1,1e9),void 0===e?e=i.rounding:m(e,0,8),r=w(o=E(new i(o),t,e)),n=A(o,t<=r||r<=i.toExpNeg,t)),n},y.toSignificantDigits=y.tosd=function(t,e){var r=this.constructor;return void 0===t?(t=r.precision,e=r.rounding):(m(t,1,1e9),void 0===e?e=r.rounding:m(e,0,8)),E(new r(this),t,e)},y.toString=y.valueOf=y.val=y.toJSON=function(){var t=w(this),e=this.constructor;return A(this,t<=e.toExpNeg||t>=e.toExpPos)};var g=function(){function t(t,e){var r,n=0,o=t.length;for(t=t.slice();o--;)r=t[o]*e+n,t[o]=r%1e7|0,n=r/1e7|0;return n&&t.unshift(n),t}function e(t,e,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;oe[o]?1:-1;break}return i}function r(t,e,r){for(var n=0;r--;)t[r]-=n,n=t[r]1;)t.shift()}return function(n,o,i,a){var u,l,s,f,p,h,d,y,v,m,b,g,x,O,j,S,P,k,A=n.constructor,M=n.s==o.s?1:-1,_=n.d,T=o.d;if(!n.s)return new A(n);if(!o.s)throw Error(c+"Division by zero");for(s=0,l=n.e-o.e,P=T.length,j=_.length,y=(d=new A(M)).d=[];T[s]==(_[s]||0);)++s;if(T[s]>(_[s]||0)&&--l,(g=null==i?i=A.precision:a?i+(w(n)-w(o))+1:i)<0)return new A(0);if(g=g/7+2|0,s=0,1==P)for(f=0,T=T[0],g++;(s1&&(T=t(T,f),_=t(_,f),P=T.length,j=_.length),O=P,m=(v=_.slice(0,P)).length;m=1e7/2&&++S;do f=0,(u=e(T,v,P,m))<0?(b=v[0],P!=m&&(b=1e7*b+(v[1]||0)),(f=b/S|0)>1?(f>=1e7&&(f=1e7-1),h=(p=t(T,f)).length,m=v.length,1==(u=e(p,v,h,m))&&(f--,r(p,P16)throw Error(s+w(t));if(!t.s)return new h(i);for(null==e?(u=!1,c=d):c=e,a=new h(.03125);t.abs().gte(.1);)t=t.times(a),f+=5;for(c+=Math.log(p(2,f))/Math.LN10*2+5|0,r=n=o=new h(i),h.precision=c;;){if(n=E(n.times(t),c),r=r.times(++l),b((a=o.plus(g(n,r,c))).d).slice(0,c)===b(o.d).slice(0,c)){for(;f--;)o=E(o.times(o),c);return h.precision=d,null==e?(u=!0,E(o,d)):o}o=a}}function w(t){for(var e=7*t.e,r=t.d[0];r>=10;r/=10)e++;return e}function O(t,e,r){if(e>t.LN10.sd())throw u=!0,r&&(t.precision=r),Error(c+"LN10 precision limit exceeded");return E(new t(t.LN10),e)}function j(t){for(var e="";t--;)e+="0";return e}function S(t,e){var r,n,o,a,l,s,f,p,h,d=1,y=t,v=y.d,m=y.constructor,x=m.precision;if(y.s<1)throw Error(c+(y.s?"NaN":"-Infinity"));if(y.eq(i))return new m(0);if(null==e?(u=!1,p=x):p=e,y.eq(10))return null==e&&(u=!0),O(m,p);if(p+=10,m.precision=p,n=(r=b(v)).charAt(0),!(15e14>Math.abs(a=w(y))))return f=O(m,p+2,x).times(a+""),y=S(new m(n+"."+r.slice(1)),p-10).plus(f),m.precision=x,null==e?(u=!0,E(y,x)):y;for(;n<7&&1!=n||1==n&&r.charAt(1)>3;)n=(r=b((y=y.times(t)).d)).charAt(0),d++;for(a=w(y),n>1?(y=new m("0."+r),a++):y=new m(n+"."+r.slice(1)),s=l=y=g(y.minus(i),y.plus(i),p),h=E(y.times(y),p),o=3;;){if(l=E(l.times(h),p),b((f=s.plus(g(l,new m(o),p))).d).slice(0,p)===b(s.d).slice(0,p))return s=s.times(2),0!==a&&(s=s.plus(O(m,p+2,x).times(a+""))),s=g(s,new m(d),p),m.precision=x,null==e?(u=!0,E(s,x)):s;s=f,o+=2}}function P(t,e){var r,n,o;for((r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),n=0;48===e.charCodeAt(n);)++n;for(o=e.length;48===e.charCodeAt(o-1);)--o;if(e=e.slice(n,o)){if(o-=n,r=r-n-1,t.e=f(r/7),t.d=[],n=(r+1)%7,r<0&&(n+=7),nd||t.e<-d))throw Error(s+r)}else t.s=0,t.e=0,t.d=[0];return t}function E(t,e,r){var n,o,i,a,c,l,h,y,v=t.d;for(a=1,i=v[0];i>=10;i/=10)a++;if((n=e-a)<0)n+=7,o=e,h=v[y=0];else{if((y=Math.ceil((n+1)/7))>=(i=v.length))return t;for(a=1,h=i=v[y];i>=10;i/=10)a++;n%=7,o=n-7+a}if(void 0!==r&&(c=h/(i=p(10,a-o-1))%10|0,l=e<0||void 0!==v[y+1]||h%i,l=r<4?(c||l)&&(0==r||r==(t.s<0?3:2)):c>5||5==c&&(4==r||l||6==r&&(n>0?o>0?h/p(10,a-o):0:v[y-1])%10&1||r==(t.s<0?8:7))),e<1||!v[0])return l?(i=w(t),v.length=1,e=e-i-1,v[0]=p(10,(7-e%7)%7),t.e=f(-e/7)||0):(v.length=1,v[0]=t.e=t.s=0),t;if(0==n?(v.length=y,i=1,y--):(v.length=y+1,i=p(10,7-n),v[y]=o>0?(h/p(10,a-o)%p(10,o)|0)*i:0),l)for(;;){if(0==y){1e7==(v[0]+=i)&&(v[0]=1,++t.e);break}if(v[y]+=i,1e7!=v[y])break;v[y--]=0,i=1}for(n=v.length;0===v[--n];)v.pop();if(u&&(t.e>d||t.e<-d))throw Error(s+w(t));return t}function k(t,e){var r,n,o,i,a,c,l,s,f,p,h=t.constructor,d=h.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new h(t),u?E(e,d):e;if(l=t.d,p=e.d,n=e.e,s=t.e,l=l.slice(),a=s-n){for((f=a<0)?(r=l,a=-a,c=p.length):(r=p,n=s,c=l.length),a>(o=Math.max(Math.ceil(d/7),c)+2)&&(a=o,r.length=1),r.reverse(),o=a;o--;)r.push(0);r.reverse()}else{for((f=(o=l.length)<(c=p.length))&&(c=o),o=0;o0;--o)l[c++]=0;for(o=p.length;o>a;){if(l[--o]0?i=i.charAt(0)+"."+i.slice(1)+j(n):a>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(o<0?"e":"e+")+o):o<0?(i="0."+j(-o-1)+i,r&&(n=r-a)>0&&(i+=j(n))):o>=a?(i+=j(o+1-a),r&&(n=r-o-1)>0&&(i=i+"."+j(n))):((n=o+1)0&&(o+1===a&&(i+="."),i+=j(n))),t.s<0?"-"+i:i}function M(t,e){if(t.length>e)return t.length=e,!0}function _(t){if(!t||"object"!=typeof t)throw Error(c+"Object expected");var e,r,n,o=["precision",1,1e9,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(e=0;e=o[e+1]&&n<=o[e+2])this[r]=n;else throw Error(l+r+": "+n)}if(void 0!==(n=t[r="LN10"])){if(n==Math.LN10)this[r]=new this(n);else throw Error(l+r+": "+n)}return this}(a=function t(e){var r,n,o;function i(t){if(!(this instanceof i))return new i(t);if(this.constructor=i,t instanceof i){this.s=t.s,this.e=t.e,this.d=(t=t.d)?t.slice():t;return}if("number"==typeof t){if(0*t!=0)throw Error(l+t);if(t>0)this.s=1;else if(t<0)t=-t,this.s=-1;else{this.s=0,this.e=0,this.d=[0];return}if(t===~~t&&t<1e7){this.e=0,this.d=[t];return}return P(this,t.toString())}if("string"!=typeof t)throw Error(l+t);if(45===t.charCodeAt(0)?(t=t.slice(1),this.s=-1):this.s=1,h.test(t))P(this,t);else throw Error(l+t)}if(i.prototype=y,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=t,i.config=i.set=_,void 0===e&&(e={}),e)for(r=0,o=["precision","rounding","toExpNeg","toExpPos","LN10"];r-1}},56883:function(t){t.exports=function(t,e,r){for(var n=-1,o=null==t?0:t.length;++n0&&i(s)?r>1?t(s,r-1,i,a,u):n(u,s):a||(u[u.length]=s)}return u}},63321:function(t,e,r){var n=r(33023)();t.exports=n},98060:function(t,e,r){var n=r(63321),o=r(43228);t.exports=function(t,e){return t&&n(t,e,o)}},92167:function(t,e,r){var n=r(67906),o=r(70235);t.exports=function(t,e){e=n(e,t);for(var r=0,i=e.length;null!=t&&re}},93012:function(t){t.exports=function(t,e){return null!=t&&e in Object(t)}},47909:function(t,e,r){var n=r(8235),o=r(31953),i=r(35281);t.exports=function(t,e,r){return e==e?i(t,e,r):n(t,o,r)}},90370:function(t,e,r){var n=r(54506),o=r(10303);t.exports=function(t){return o(t)&&"[object Arguments]"==n(t)}},56318:function(t,e,r){var n=r(6791),o=r(10303);t.exports=function t(e,r,i,a,u){return e===r||(null!=e&&null!=r&&(o(e)||o(r))?n(e,r,i,a,t,u):e!=e&&r!=r)}},6791:function(t,e,r){var n=r(85885),o=r(97638),i=r(88030),a=r(64974),u=r(81690),c=r(25614),l=r(98051),s=r(9792),f="[object Arguments]",p="[object Array]",h="[object Object]",d=Object.prototype.hasOwnProperty;t.exports=function(t,e,r,y,v,m){var b=c(t),g=c(e),x=b?p:u(t),w=g?p:u(e);x=x==f?h:x,w=w==f?h:w;var O=x==h,j=w==h,S=x==w;if(S&&l(t)){if(!l(e))return!1;b=!0,O=!1}if(S&&!O)return m||(m=new n),b||s(t)?o(t,e,r,y,v,m):i(t,e,x,r,y,v,m);if(!(1&r)){var P=O&&d.call(t,"__wrapped__"),E=j&&d.call(e,"__wrapped__");if(P||E){var k=P?t.value():t,A=E?e.value():e;return m||(m=new n),v(k,A,r,y,m)}}return!!S&&(m||(m=new n),a(t,e,r,y,v,m))}},62538:function(t,e,r){var n=r(85885),o=r(56318);t.exports=function(t,e,r,i){var a=r.length,u=a,c=!i;if(null==t)return!u;for(t=Object(t);a--;){var l=r[a];if(c&&l[2]?l[1]!==t[l[0]]:!(l[0]in t))return!1}for(;++ao?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n=200){var y=e?null:u(t);if(y)return c(y);p=!1,s=a,d=new n}else d=e?[]:h;t:for(;++l=o?t:n(t,e,r)}},1536:function(t,e,r){var n=r(78371);t.exports=function(t,e){if(t!==e){var r=void 0!==t,o=null===t,i=t==t,a=n(t),u=void 0!==e,c=null===e,l=e==e,s=n(e);if(!c&&!s&&!a&&t>e||a&&u&&l&&!c&&!s||o&&u&&l||!r&&l||!i)return 1;if(!o&&!a&&!s&&t=c)return l;return l*("desc"==r[o]?-1:1)}}return t.index-e.index}},92077:function(t,e,r){var n=r(74288)["__core-js_shared__"];t.exports=n},97930:function(t,e,r){var n=r(5629);t.exports=function(t,e){return function(r,o){if(null==r)return r;if(!n(r))return t(r,o);for(var i=r.length,a=e?i:-1,u=Object(r);(e?a--:++a-1?u[c?e[l]:l]:void 0}}},35464:function(t,e,r){var n=r(19608),o=r(49639),i=r(175);t.exports=function(t){return function(e,r,a){return a&&"number"!=typeof a&&o(e,r,a)&&(r=a=void 0),e=i(e),void 0===r?(r=e,e=0):r=i(r),a=void 0===a?es))return!1;var p=c.get(t),h=c.get(e);if(p&&h)return p==e&&h==t;var d=-1,y=!0,v=2&r?new n:void 0;for(c.set(t,e),c.set(e,t);++d-1&&t%1==0&&t-1}},13368:function(t,e,r){var n=r(24457);t.exports=function(t,e){var r=this.__data__,o=n(r,t);return o<0?(++this.size,r.push([t,e])):r[o][1]=e,this}},38764:function(t,e,r){var n=r(9855),o=r(99078),i=r(88675);t.exports=function(){this.size=0,this.__data__={hash:new n,map:new(i||o),string:new n}}},78615:function(t,e,r){var n=r(1507);t.exports=function(t){var e=n(this,t).delete(t);return this.size-=e?1:0,e}},83391:function(t,e,r){var n=r(1507);t.exports=function(t){return n(this,t).get(t)}},53483:function(t,e,r){var n=r(1507);t.exports=function(t){return n(this,t).has(t)}},74724:function(t,e,r){var n=r(1507);t.exports=function(t,e){var r=n(this,t),o=r.size;return r.set(t,e),this.size+=r.size==o?0:1,this}},22523:function(t){t.exports=function(t){var e=-1,r=Array(t.size);return t.forEach(function(t,n){r[++e]=[n,t]}),r}},47073:function(t){t.exports=function(t,e){return function(r){return null!=r&&r[t]===e&&(void 0!==e||t in Object(r))}}},23787:function(t,e,r){var n=r(50967);t.exports=function(t){var e=n(t,function(t){return 500===r.size&&r.clear(),t}),r=e.cache;return e}},20453:function(t,e,r){var n=r(39866)(Object,"create");t.exports=n},77184:function(t,e,r){var n=r(45070)(Object.keys,Object);t.exports=n},39931:function(t,e,r){t=r.nmd(t);var n=r(17071),o=e&&!e.nodeType&&e,i=o&&t&&!t.nodeType&&t,a=i&&i.exports===o&&n.process,u=function(){try{var t=i&&i.require&&i.require("util").types;if(t)return t;return a&&a.binding&&a.binding("util")}catch(t){}}();t.exports=u},45070:function(t){t.exports=function(t,e){return function(r){return t(e(r))}}},49478:function(t,e,r){var n=r(68680),o=Math.max;t.exports=function(t,e,r){return e=o(void 0===e?t.length-1:e,0),function(){for(var i=arguments,a=-1,u=o(i.length-e,0),c=Array(u);++a0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}},84092:function(t,e,r){var n=r(99078);t.exports=function(){this.__data__=new n,this.size=0}},31663:function(t){t.exports=function(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}},69135:function(t){t.exports=function(t){return this.__data__.get(t)}},39552:function(t){t.exports=function(t){return this.__data__.has(t)}},8381:function(t,e,r){var n=r(99078),o=r(88675),i=r(76219);t.exports=function(t,e){var r=this.__data__;if(r instanceof n){var a=r.__data__;if(!o||a.length<199)return a.push([t,e]),this.size=++r.size,this;r=this.__data__=new i(a)}return r.set(t,e),this.size=r.size,this}},35281:function(t){t.exports=function(t,e,r){for(var n=r-1,o=t.length;++n-1&&t%1==0&&t<=9007199254740991}},82559:function(t,e,r){var n=r(22345);t.exports=function(t){return n(t)&&t!=+t}},77571:function(t){t.exports=function(t){return null==t}},22345:function(t,e,r){var n=r(54506),o=r(10303);t.exports=function(t){return"number"==typeof t||o(t)&&"[object Number]"==n(t)}},90231:function(t,e,r){var n=r(54506),o=r(62602),i=r(10303),a=Object.prototype,u=Function.prototype.toString,c=a.hasOwnProperty,l=u.call(Object);t.exports=function(t){if(!i(t)||"[object Object]"!=n(t))return!1;var e=o(t);if(null===e)return!0;var r=c.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&u.call(r)==l}},42715:function(t,e,r){var n=r(54506),o=r(25614),i=r(10303);t.exports=function(t){return"string"==typeof t||!o(t)&&i(t)&&"[object String]"==n(t)}},9792:function(t,e,r){var n=r(59332),o=r(23305),i=r(39931),a=i&&i.isTypedArray,u=a?o(a):n;t.exports=u},43228:function(t,e,r){var n=r(28579),o=r(4578),i=r(5629);t.exports=function(t){return i(t)?n(t):o(t)}},86185:function(t){t.exports=function(t){var e=null==t?0:t.length;return e?t[e-1]:void 0}},89238:function(t,e,r){var n=r(73819),o=r(88157),i=r(24240),a=r(25614);t.exports=function(t,e){return(a(t)?n:i)(t,o(e,3))}},41443:function(t,e,r){var n=r(83023),o=r(98060),i=r(88157);t.exports=function(t,e){var r={};return e=i(e,3),o(t,function(t,o,i){n(r,o,e(t,o,i))}),r}},95645:function(t,e,r){var n=r(67646),o=r(58905),i=r(79586);t.exports=function(t){return t&&t.length?n(t,i,o):void 0}},50967:function(t,e,r){var n=r(76219);function o(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw TypeError("Expected a function");var r=function(){var n=arguments,o=e?e.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var a=t.apply(this,n);return r.cache=i.set(o,a)||i,a};return r.cache=new(o.Cache||n),r}o.Cache=n,t.exports=o},99008:function(t,e,r){var n=r(67646),o=r(20121),i=r(79586);t.exports=function(t){return t&&t.length?n(t,i,o):void 0}},93810:function(t){t.exports=function(){}},22350:function(t,e,r){var n=r(18155),o=r(73584),i=r(67352),a=r(70235);t.exports=function(t){return i(t)?n(a(t)):o(t)}},99676:function(t,e,r){var n=r(35464)();t.exports=n},33645:function(t,e,r){var n=r(25253),o=r(88157),i=r(12327),a=r(25614),u=r(49639);t.exports=function(t,e,r){var c=a(t)?n:i;return r&&u(t,e,r)&&(e=void 0),c(t,o(e,3))}},34935:function(t,e,r){var n=r(72569),o=r(84046),i=r(44843),a=r(49639),u=i(function(t,e){if(null==t)return[];var r=e.length;return r>1&&a(t,e[0],e[1])?e=[]:r>2&&a(e[0],e[1],e[2])&&(e=[e[0]]),o(t,n(e,1),[])});t.exports=u},55716:function(t){t.exports=function(){return[]}},7406:function(t){t.exports=function(){return!1}},37065:function(t,e,r){var n=r(7310),o=r(28302);t.exports=function(t,e,r){var i=!0,a=!0;if("function"!=typeof t)throw TypeError("Expected a function");return o(r)&&(i="leading"in r?!!r.leading:i,a="trailing"in r?!!r.trailing:a),n(t,e,{leading:i,maxWait:e,trailing:a})}},175:function(t,e,r){var n=r(6660),o=1/0;t.exports=function(t){return t?(t=n(t))===o||t===-o?(t<0?-1:1)*17976931348623157e292:t==t?t:0:0===t?t:0}},85759:function(t,e,r){var n=r(175);t.exports=function(t){var e=n(t),r=e%1;return e==e?r?e-r:e:0}},3641:function(t,e,r){var n=r(65020);t.exports=function(t){return null==t?"":n(t)}},47230:function(t,e,r){var n=r(88157),o=r(13826);t.exports=function(t,e){return t&&t.length?o(t,n(e,2)):[]}},75551:function(t,e,r){var n=r(80675)("toUpperCase");t.exports=n},48049:function(t,e,r){"use strict";var n=r(14397);function o(){}function i(){}i.resetWarningCache=o,t.exports=function(){function t(t,e,r,o,i,a){if(a!==n){var u=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}function e(){return t}t.isRequired=t;var r={array:t,bigint:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,elementType:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e,checkPropTypes:i,resetWarningCache:o};return r.PropTypes=r,r}},40718:function(t,e,r){t.exports=r(48049)()},14397:function(t){"use strict";t.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},84735:function(t,e,r){"use strict";r.d(e,{ZP:function(){return tS}});var n=r(2265),o=r(40718),i=r.n(o),a=Object.getOwnPropertyNames,u=Object.getOwnPropertySymbols,c=Object.prototype.hasOwnProperty;function l(t,e){return function(r,n,o){return t(r,n,o)&&e(r,n,o)}}function s(t){return function(e,r,n){if(!e||!r||"object"!=typeof e||"object"!=typeof r)return t(e,r,n);var o=n.cache,i=o.get(e),a=o.get(r);if(i&&a)return i===r&&a===e;o.set(e,r),o.set(r,e);var u=t(e,r,n);return o.delete(e),o.delete(r),u}}function f(t){return a(t).concat(u(t))}var p=Object.hasOwn||function(t,e){return c.call(t,e)};function h(t,e){return t===e||!t&&!e&&t!=t&&e!=e}var d=Object.getOwnPropertyDescriptor,y=Object.keys;function v(t,e,r){var n=t.length;if(e.length!==n)return!1;for(;n-- >0;)if(!r.equals(t[n],e[n],n,n,t,e,r))return!1;return!0}function m(t,e){return h(t.getTime(),e.getTime())}function b(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function g(t,e){return t===e}function x(t,e,r){var n,o,i=t.size;if(i!==e.size)return!1;if(!i)return!0;for(var a=Array(i),u=t.entries(),c=0;(n=u.next())&&!n.done;){for(var l=e.entries(),s=!1,f=0;(o=l.next())&&!o.done;){if(a[f]){f++;continue}var p=n.value,h=o.value;if(r.equals(p[0],h[0],c,f,t,e,r)&&r.equals(p[1],h[1],p[0],h[0],t,e,r)){s=a[f]=!0;break}f++}if(!s)return!1;c++}return!0}function w(t,e,r){var n=y(t),o=n.length;if(y(e).length!==o)return!1;for(;o-- >0;)if(!A(t,e,r,n[o]))return!1;return!0}function O(t,e,r){var n,o,i,a=f(t),u=a.length;if(f(e).length!==u)return!1;for(;u-- >0;)if(!A(t,e,r,n=a[u])||(o=d(t,n),i=d(e,n),(o||i)&&(!o||!i||o.configurable!==i.configurable||o.enumerable!==i.enumerable||o.writable!==i.writable)))return!1;return!0}function j(t,e){return h(t.valueOf(),e.valueOf())}function S(t,e){return t.source===e.source&&t.flags===e.flags}function P(t,e,r){var n,o,i=t.size;if(i!==e.size)return!1;if(!i)return!0;for(var a=Array(i),u=t.values();(n=u.next())&&!n.done;){for(var c=e.values(),l=!1,s=0;(o=c.next())&&!o.done;){if(!a[s]&&r.equals(n.value,o.value,n.value,o.value,t,e,r)){l=a[s]=!0;break}s++}if(!l)return!1}return!0}function E(t,e){var r=t.length;if(e.length!==r)return!1;for(;r-- >0;)if(t[r]!==e[r])return!1;return!0}function k(t,e){return t.hostname===e.hostname&&t.pathname===e.pathname&&t.protocol===e.protocol&&t.port===e.port&&t.hash===e.hash&&t.username===e.username&&t.password===e.password}function A(t,e,r,n){return("_owner"===n||"__o"===n||"__v"===n)&&(!!t.$$typeof||!!e.$$typeof)||p(e,n)&&r.equals(t[n],e[n],n,n,t,e,r)}var M=Array.isArray,_="undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView:null,T=Object.assign,C=Object.prototype.toString.call.bind(Object.prototype.toString),N=D();function D(t){void 0===t&&(t={});var e,r,n,o,i,a,u,c,f,p,d,y,A,N,D=t.circular,I=t.createInternalComparator,L=t.createState,B=t.strict,R=(r=(e=function(t){var e=t.circular,r=t.createCustomConfig,n=t.strict,o={areArraysEqual:n?O:v,areDatesEqual:m,areErrorsEqual:b,areFunctionsEqual:g,areMapsEqual:n?l(x,O):x,areNumbersEqual:h,areObjectsEqual:n?O:w,arePrimitiveWrappersEqual:j,areRegExpsEqual:S,areSetsEqual:n?l(P,O):P,areTypedArraysEqual:n?O:E,areUrlsEqual:k,unknownTagComparators:void 0};if(r&&(o=T({},o,r(o))),e){var i=s(o.areArraysEqual),a=s(o.areMapsEqual),u=s(o.areObjectsEqual),c=s(o.areSetsEqual);o=T({},o,{areArraysEqual:i,areMapsEqual:a,areObjectsEqual:u,areSetsEqual:c})}return o}(t)).areArraysEqual,n=e.areDatesEqual,o=e.areErrorsEqual,i=e.areFunctionsEqual,a=e.areMapsEqual,u=e.areNumbersEqual,c=e.areObjectsEqual,f=e.arePrimitiveWrappersEqual,p=e.areRegExpsEqual,d=e.areSetsEqual,y=e.areTypedArraysEqual,A=e.areUrlsEqual,N=e.unknownTagComparators,function(t,e,l){if(t===e)return!0;if(null==t||null==e)return!1;var s=typeof t;if(s!==typeof e)return!1;if("object"!==s)return"number"===s?u(t,e,l):"function"===s&&i(t,e,l);var h=t.constructor;if(h!==e.constructor)return!1;if(h===Object)return c(t,e,l);if(M(t))return r(t,e,l);if(null!=_&&_(t))return y(t,e,l);if(h===Date)return n(t,e,l);if(h===RegExp)return p(t,e,l);if(h===Map)return a(t,e,l);if(h===Set)return d(t,e,l);var v=C(t);if("[object Date]"===v)return n(t,e,l);if("[object RegExp]"===v)return p(t,e,l);if("[object Map]"===v)return a(t,e,l);if("[object Set]"===v)return d(t,e,l);if("[object Object]"===v)return"function"!=typeof t.then&&"function"!=typeof e.then&&c(t,e,l);if("[object URL]"===v)return A(t,e,l);if("[object Error]"===v)return o(t,e,l);if("[object Arguments]"===v)return c(t,e,l);if("[object Boolean]"===v||"[object Number]"===v||"[object String]"===v)return f(t,e,l);if(N){var m=N[v];if(!m){var b=null!=t?t[Symbol.toStringTag]:void 0;b&&(m=N[b])}if(m)return m(t,e,l)}return!1}),z=I?I(R):function(t,e,r,n,o,i,a){return R(t,e,a)};return function(t){var e=t.circular,r=t.comparator,n=t.createState,o=t.equals,i=t.strict;if(n)return function(t,a){var u=n(),c=u.cache;return r(t,a,{cache:void 0===c?e?new WeakMap:void 0:c,equals:o,meta:u.meta,strict:i})};if(e)return function(t,e){return r(t,e,{cache:new WeakMap,equals:o,meta:void 0,strict:i})};var a={cache:void 0,equals:o,meta:void 0,strict:i};return function(t,e){return r(t,e,a)}}({circular:void 0!==D&&D,comparator:R,createState:L,equals:z,strict:void 0!==B&&B})}function I(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=-1;requestAnimationFrame(function n(o){if(r<0&&(r=o),o-r>e)t(o),r=-1;else{var i;i=n,"undefined"!=typeof requestAnimationFrame&&requestAnimationFrame(i)}})}function L(t){return(L="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function B(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);rt.length)&&(e=t.length);for(var r=0,n=Array(e);r=0&&t<=1}),"[configBezier]: arguments should be x1, y1, x2, y2 of [0, 1] instead received %s",n);var p=V(i,u),h=V(a,c),d=(t=i,e=u,function(r){var n;return G([].concat(function(t){if(Array.isArray(t))return H(t)}(n=X(t,e).map(function(t,e){return t*e}).slice(1))||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(n)||Y(n)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(),[0]),r)}),y=function(t){for(var e=t>1?1:t,r=e,n=0;n<8;++n){var o,i=p(r)-e,a=d(r);if(1e-4>Math.abs(i-e)||a<1e-4)break;r=(o=r-i/a)>1?1:o<0?0:o}return h(r)};return y.isStepper=!1,y},Q=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.stiff,r=void 0===e?100:e,n=t.damping,o=void 0===n?8:n,i=t.dt,a=void 0===i?17:i,u=function(t,e,n){var i=n+(-(t-e)*r-n*o)*a/1e3,u=n*a/1e3+t;return 1e-4>Math.abs(u-e)&&1e-4>Math.abs(i)?[e,0]:[u,i]};return u.isStepper=!0,u.dt=a,u},J=function(){for(var t=arguments.length,e=Array(t),r=0;rt.length)&&(e=t.length);for(var r=0,n=Array(e);rt.length)&&(e=t.length);for(var r=0,n=Array(e);r0?r[o-1]:n,p=l||Object.keys(c);if("function"==typeof u||"spring"===u)return[].concat(th(t),[e.runJSAnimation.bind(e,{from:f.style,to:c,duration:i,easing:u}),i]);var h=Z(p,i,u),d=tv(tv(tv({},f.style),c),{},{transition:h});return[].concat(th(t),[d,i,s]).filter($)},[a,Math.max(void 0===u?0:u,n)])),[t.onAnimationEnd]))}},{key:"runAnimation",value:function(t){if(!this.manager){var e,r,n;this.manager=(e=function(){return null},r=!1,n=function t(n){if(!r){if(Array.isArray(n)){if(!n.length)return;var o=function(t){if(Array.isArray(t))return t}(n)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(n)||function(t,e){if(t){if("string"==typeof t)return B(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return B(t,void 0)}}(n)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(),i=o[0],a=o.slice(1);if("number"==typeof i){I(t.bind(null,a),i);return}t(i),I(t.bind(null,a));return}"object"===L(n)&&e(n),"function"==typeof n&&n()}},{stop:function(){r=!0},start:function(t){r=!1,n(t)},subscribe:function(t){return e=t,function(){e=function(){return null}}}})}var o=t.begin,i=t.duration,a=t.attributeName,u=t.to,c=t.easing,l=t.onAnimationStart,s=t.onAnimationEnd,f=t.steps,p=t.children,h=this.manager;if(this.unSubscribe=h.subscribe(this.handleStyleChange),"function"==typeof c||"function"==typeof p||"spring"===c){this.runJSAnimation(t);return}if(f.length>1){this.runStepAnimation(t);return}var d=a?tm({},a,u):u,y=Z(Object.keys(d),i,c);h.start([l,o,tv(tv({},d),{},{transition:y}),i,s])}},{key:"render",value:function(){var t=this.props,e=t.children,r=(t.begin,t.duration),o=(t.attributeName,t.easing,t.isActive),i=(t.steps,t.from,t.to,t.canBegin,t.onAnimationEnd,t.shouldReAnimate,t.onAnimationReStart,function(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r,n,o={},i=Object.keys(t);for(n=0;n=0||(o[r]=t[r]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,tp)),a=n.Children.count(e),u=this.state.style;if("function"==typeof e)return e(u);if(!o||0===a||r<=0)return e;var c=function(t){var e=t.props,r=e.style,o=e.className;return(0,n.cloneElement)(t,tv(tv({},i),{},{style:tv(tv({},void 0===r?{}:r),u),className:o}))};return 1===a?c(n.Children.only(e)):n.createElement("div",null,n.Children.map(e,function(t){return c(t)}))}}],function(t,e){for(var r=0;r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,w),i=parseInt("".concat(r),10),a=parseInt("".concat(n),10),u=parseInt("".concat(e.height||o.height),10),c=parseInt("".concat(e.width||o.width),10);return P(P(P(P(P({},e),o),i?{x:i}:{}),a?{y:a}:{}),{},{height:u,width:c,name:e.name,radius:e.radius})}function k(t){return n.createElement(x.bn,j({shapeType:"rectangle",propTransformer:E,activeClassName:"recharts-active-bar"},t))}var A=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return function(r,n){if("number"==typeof t)return t;var o=(0,d.hj)(r)||(0,d.Rw)(r);return o?t(r,n):(o||(0,g.Z)(!1),e)}},M=["value","background"];function _(t){return(_="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function T(){return(T=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(e,M);if(!u)return null;var l=N(N(N(N(N({},c),{},{fill:"#eee"},u),a),(0,b.bw)(t.props,e,r)),{},{onAnimationStart:t.handleAnimationStart,onAnimationEnd:t.handleAnimationEnd,dataKey:o,index:r,className:"recharts-bar-background-rectangle"});return n.createElement(k,T({key:"background-bar-".concat(r),option:t.props.background,isActive:r===i},l))})}},{key:"renderErrorBar",value:function(t,e){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var r=this.props,o=r.data,i=r.xAxis,a=r.yAxis,u=r.layout,c=r.children,l=(0,y.NN)(c,f.W);if(!l)return null;var p="vertical"===u?o[0].height/2:o[0].width/2,h=function(t,e){var r=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:r,errorVal:(0,m.F$)(t,e)}};return n.createElement(s.m,{clipPath:t?"url(#clipPath-".concat(e,")"):null},l.map(function(t){return n.cloneElement(t,{key:"error-bar-".concat(e,"-").concat(t.props.dataKey),data:o,xAxis:i,yAxis:a,layout:u,offset:p,dataPointFormatter:h})}))}},{key:"render",value:function(){var t=this.props,e=t.hide,r=t.data,i=t.className,a=t.xAxis,u=t.yAxis,c=t.left,f=t.top,p=t.width,d=t.height,y=t.isAnimationActive,v=t.background,m=t.id;if(e||!r||!r.length)return null;var b=this.state.isAnimationFinished,g=(0,o.Z)("recharts-bar",i),x=a&&a.allowDataOverflow,w=u&&u.allowDataOverflow,O=x||w,j=l()(m)?this.id:m;return n.createElement(s.m,{className:g},x||w?n.createElement("defs",null,n.createElement("clipPath",{id:"clipPath-".concat(j)},n.createElement("rect",{x:x?c:c-p/2,y:w?f:f-d/2,width:x?p:2*p,height:w?d:2*d}))):null,n.createElement(s.m,{className:"recharts-bar-rectangles",clipPath:O?"url(#clipPath-".concat(j,")"):null},v?this.renderBackground():null,this.renderRectangles()),this.renderErrorBar(O,j),(!y||b)&&h.e.renderCallByParent(this.props,r))}}],r=[{key:"getDerivedStateFromProps",value:function(t,e){return t.animationId!==e.prevAnimationId?{prevAnimationId:t.animationId,curData:t.data,prevData:e.curData}:t.data!==e.curData?{curData:t.data}:null}}],e&&D(a.prototype,e),r&&D(a,r),Object.defineProperty(a,"prototype",{writable:!1}),a}(n.PureComponent);R(U,"displayName","Bar"),R(U,"defaultProps",{xAxisId:0,yAxisId:0,legendType:"rect",minPointSize:0,hide:!1,data:[],layout:"vertical",activeBar:!1,isAnimationActive:!v.x.isSsr,animationBegin:0,animationDuration:400,animationEasing:"ease"}),R(U,"getComposedData",function(t){var e=t.props,r=t.item,n=t.barPosition,o=t.bandSize,i=t.xAxis,a=t.yAxis,u=t.xAxisTicks,c=t.yAxisTicks,l=t.stackedData,s=t.dataStartIndex,f=t.displayedData,h=t.offset,v=(0,m.Bu)(n,r);if(!v)return null;var b=e.layout,g=r.type.defaultProps,x=void 0!==g?N(N({},g),r.props):r.props,w=x.dataKey,O=x.children,j=x.minPointSize,S="horizontal"===b?a:i,P=l?S.scale.domain():null,E=(0,m.Yj)({numericAxis:S}),k=(0,y.NN)(O,p.b),M=f.map(function(t,e){l?f=(0,m.Vv)(l[s+e],P):Array.isArray(f=(0,m.F$)(t,w))||(f=[E,f]);var n=A(j,U.defaultProps.minPointSize)(f[1],e);if("horizontal"===b){var f,p,h,y,g,x,O,S=[a.scale(f[0]),a.scale(f[1])],M=S[0],_=S[1];p=(0,m.Fy)({axis:i,ticks:u,bandSize:o,offset:v.offset,entry:t,index:e}),h=null!==(O=null!=_?_:M)&&void 0!==O?O:void 0,y=v.size;var T=M-_;if(g=Number.isNaN(T)?0:T,x={x:p,y:a.y,width:y,height:a.height},Math.abs(n)>0&&Math.abs(g)0&&Math.abs(y)=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function P(t,e){for(var r=0;r0?this.props:d)),o<=0||a<=0||!y||!y.length)?null:n.createElement(s.m,{className:(0,c.Z)("recharts-cartesian-axis",l),ref:function(e){t.layerReference=e}},r&&this.renderAxisLine(),this.renderTicks(y,this.state.fontSize,this.state.letterSpacing),p._.renderCallByParent(this.props))}}],r=[{key:"renderTickItem",value:function(t,e,r){var o=(0,c.Z)(e.className,"recharts-cartesian-axis-tick-value");return n.isValidElement(t)?n.cloneElement(t,j(j({},e),{},{className:o})):i()(t)?t(j(j({},e),{},{className:o})):n.createElement(f.x,w({},e,{className:"recharts-cartesian-axis-tick-value"}),r)}}],e&&P(o.prototype,e),r&&P(o,r),Object.defineProperty(o,"prototype",{writable:!1}),o}(n.Component);M(T,"displayName","CartesianAxis"),M(T,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"})},56940:function(t,e,r){"use strict";r.d(e,{q:function(){return M}});var n=r(2265),o=r(86757),i=r.n(o),a=r(1175),u=r(16630),c=r(82944),l=r(85355),s=r(78242),f=r(80285),p=r(25739),h=["x1","y1","x2","y2","key"],d=["offset"];function y(t){return(y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function v(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function m(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}var x=function(t){var e=t.fill;if(!e||"none"===e)return null;var r=t.fillOpacity,o=t.x,i=t.y,a=t.width,u=t.height,c=t.ry;return n.createElement("rect",{x:o,y:i,ry:c,width:a,height:u,stroke:"none",fill:e,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function w(t,e){var r;if(n.isValidElement(t))r=n.cloneElement(t,e);else if(i()(t))r=t(e);else{var o=e.x1,a=e.y1,u=e.x2,l=e.y2,s=e.key,f=g(e,h),p=(0,c.L6)(f,!1),y=(p.offset,g(p,d));r=n.createElement("line",b({},y,{x1:o,y1:a,x2:u,y2:l,fill:"none",key:s}))}return r}function O(t){var e=t.x,r=t.width,o=t.horizontal,i=void 0===o||o,a=t.horizontalPoints;if(!i||!a||!a.length)return null;var u=a.map(function(n,o){return w(i,m(m({},t),{},{x1:e,y1:n,x2:e+r,y2:n,key:"line-".concat(o),index:o}))});return n.createElement("g",{className:"recharts-cartesian-grid-horizontal"},u)}function j(t){var e=t.y,r=t.height,o=t.vertical,i=void 0===o||o,a=t.verticalPoints;if(!i||!a||!a.length)return null;var u=a.map(function(n,o){return w(i,m(m({},t),{},{x1:n,y1:e,x2:n,y2:e+r,key:"line-".concat(o),index:o}))});return n.createElement("g",{className:"recharts-cartesian-grid-vertical"},u)}function S(t){var e=t.horizontalFill,r=t.fillOpacity,o=t.x,i=t.y,a=t.width,u=t.height,c=t.horizontalPoints,l=t.horizontal;if(!(void 0===l||l)||!e||!e.length)return null;var s=c.map(function(t){return Math.round(t+i-i)}).sort(function(t,e){return t-e});i!==s[0]&&s.unshift(0);var f=s.map(function(t,c){var l=s[c+1]?s[c+1]-t:i+u-t;if(l<=0)return null;var f=c%e.length;return n.createElement("rect",{key:"react-".concat(c),y:t,x:o,height:l,width:a,stroke:"none",fill:e[f],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return n.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},f)}function P(t){var e=t.vertical,r=t.verticalFill,o=t.fillOpacity,i=t.x,a=t.y,u=t.width,c=t.height,l=t.verticalPoints;if(!(void 0===e||e)||!r||!r.length)return null;var s=l.map(function(t){return Math.round(t+i-i)}).sort(function(t,e){return t-e});i!==s[0]&&s.unshift(0);var f=s.map(function(t,e){var l=s[e+1]?s[e+1]-t:i+u-t;if(l<=0)return null;var f=e%r.length;return n.createElement("rect",{key:"react-".concat(e),x:t,y:a,width:l,height:c,stroke:"none",fill:r[f],fillOpacity:o,className:"recharts-cartesian-grid-bg"})});return n.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},f)}var E=function(t,e){var r=t.xAxis,n=t.width,o=t.height,i=t.offset;return(0,l.Rf)((0,s.f)(m(m(m({},f.O.defaultProps),r),{},{ticks:(0,l.uY)(r,!0),viewBox:{x:0,y:0,width:n,height:o}})),i.left,i.left+i.width,e)},k=function(t,e){var r=t.yAxis,n=t.width,o=t.height,i=t.offset;return(0,l.Rf)((0,s.f)(m(m(m({},f.O.defaultProps),r),{},{ticks:(0,l.uY)(r,!0),viewBox:{x:0,y:0,width:n,height:o}})),i.top,i.top+i.height,e)},A={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function M(t){var e,r,o,c,l,s,f=(0,p.zn)(),h=(0,p.Mw)(),d=(0,p.qD)(),v=m(m({},t),{},{stroke:null!==(e=t.stroke)&&void 0!==e?e:A.stroke,fill:null!==(r=t.fill)&&void 0!==r?r:A.fill,horizontal:null!==(o=t.horizontal)&&void 0!==o?o:A.horizontal,horizontalFill:null!==(c=t.horizontalFill)&&void 0!==c?c:A.horizontalFill,vertical:null!==(l=t.vertical)&&void 0!==l?l:A.vertical,verticalFill:null!==(s=t.verticalFill)&&void 0!==s?s:A.verticalFill,x:(0,u.hj)(t.x)?t.x:d.left,y:(0,u.hj)(t.y)?t.y:d.top,width:(0,u.hj)(t.width)?t.width:d.width,height:(0,u.hj)(t.height)?t.height:d.height}),g=v.x,w=v.y,M=v.width,_=v.height,T=v.syncWithTicks,C=v.horizontalValues,N=v.verticalValues,D=(0,p.CW)(),I=(0,p.Nf)();if(!(0,u.hj)(M)||M<=0||!(0,u.hj)(_)||_<=0||!(0,u.hj)(g)||g!==+g||!(0,u.hj)(w)||w!==+w)return null;var L=v.verticalCoordinatesGenerator||E,B=v.horizontalCoordinatesGenerator||k,R=v.horizontalPoints,z=v.verticalPoints;if((!R||!R.length)&&i()(B)){var U=C&&C.length,F=B({yAxis:I?m(m({},I),{},{ticks:U?C:I.ticks}):void 0,width:f,height:h,offset:d},!!U||T);(0,a.Z)(Array.isArray(F),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(y(F),"]")),Array.isArray(F)&&(R=F)}if((!z||!z.length)&&i()(L)){var $=N&&N.length,q=L({xAxis:D?m(m({},D),{},{ticks:$?N:D.ticks}):void 0,width:f,height:h,offset:d},!!$||T);(0,a.Z)(Array.isArray(q),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(y(q),"]")),Array.isArray(q)&&(z=q)}return n.createElement("g",{className:"recharts-cartesian-grid"},n.createElement(x,{fill:v.fill,fillOpacity:v.fillOpacity,x:v.x,y:v.y,width:v.width,height:v.height,ry:v.ry}),n.createElement(O,b({},v,{offset:d,horizontalPoints:R,xAxis:D,yAxis:I})),n.createElement(j,b({},v,{offset:d,verticalPoints:z,xAxis:D,yAxis:I})),n.createElement(S,b({},v,{horizontalPoints:R})),n.createElement(P,b({},v,{verticalPoints:z})))}M.displayName="CartesianGrid"},13137:function(t,e,r){"use strict";r.d(e,{W:function(){return v}});var n=r(2265),o=r(69398),i=r(9841),a=r(82944),u=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function c(t){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function l(){return(l=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,u),m=(0,a.L6)(v,!1);"x"===this.props.direction&&"number"!==d.type&&(0,o.Z)(!1);var b=p.map(function(t){var o,a,u=h(t,f),p=u.x,v=u.y,b=u.value,g=u.errorVal;if(!g)return null;var x=[];if(Array.isArray(g)){var w=function(t){if(Array.isArray(t))return t}(g)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{for(i=(r=r.call(t)).next;!(c=(n=i.call(r)).done)&&(u.push(n.value),2!==u.length);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(g,2)||function(t,e){if(t){if("string"==typeof t)return s(t,2);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return s(t,2)}}(g,2)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}();o=w[0],a=w[1]}else o=a=g;if("vertical"===r){var O=d.scale,j=v+e,S=j+c,P=j-c,E=O(b-o),k=O(b+a);x.push({x1:k,y1:S,x2:k,y2:P}),x.push({x1:E,y1:j,x2:k,y2:j}),x.push({x1:E,y1:S,x2:E,y2:P})}else if("horizontal"===r){var A=y.scale,M=p+e,_=M-c,T=M+c,C=A(b-o),N=A(b+a);x.push({x1:_,y1:N,x2:T,y2:N}),x.push({x1:M,y1:C,x2:M,y2:N}),x.push({x1:_,y1:C,x2:T,y2:C})}return n.createElement(i.m,l({className:"recharts-errorBar",key:"bar-".concat(x.map(function(t){return"".concat(t.x1,"-").concat(t.x2,"-").concat(t.y1,"-").concat(t.y2)}))},m),x.map(function(t){return n.createElement("line",l({},t,{key:"line-".concat(t.x1,"-").concat(t.x2,"-").concat(t.y1,"-").concat(t.y2)}))}))});return n.createElement(i.m,{className:"recharts-errorBars"},b)}}],function(t,e){for(var r=0;rt*o)return!1;var i=r();return t*(e-t*i/2-n)>=0&&t*(e+t*i/2-o)<=0}function f(t){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function p(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function h(t){for(var e=1;e=2?(0,i.uY)(m[1].coordinate-m[0].coordinate):1,M=(n="width"===P,f=b.x,p=b.y,d=b.width,y=b.height,1===A?{start:n?f:p,end:n?f+d:p+y}:{start:n?f+d:p+y,end:n?f:p});return"equidistantPreserveStart"===w?function(t,e,r,n,o){for(var i,a=(n||[]).slice(),u=e.start,c=e.end,f=0,p=1,h=u;p<=a.length;)if(i=function(){var e,i=null==n?void 0:n[f];if(void 0===i)return{v:l(n,p)};var a=f,d=function(){return void 0===e&&(e=r(i,a)),e},y=i.coordinate,v=0===f||s(t,y,d,h,c);v||(f=0,h=u,p+=1),v&&(h=y+t*(d()/2+o),f+=p)}())return i.v;return[]}(A,M,k,m,g):("preserveStart"===w||"preserveStartEnd"===w?function(t,e,r,n,o,i){var a=(n||[]).slice(),u=a.length,c=e.start,l=e.end;if(i){var f=n[u-1],p=r(f,u-1),d=t*(f.coordinate+t*p/2-l);a[u-1]=f=h(h({},f),{},{tickCoord:d>0?f.coordinate-d*t:f.coordinate}),s(t,f.tickCoord,function(){return p},c,l)&&(l=f.tickCoord-t*(p/2+o),a[u-1]=h(h({},f),{},{isShow:!0}))}for(var y=i?u-1:u,v=function(e){var n,i=a[e],u=function(){return void 0===n&&(n=r(i,e)),n};if(0===e){var f=t*(i.coordinate-t*u()/2-c);a[e]=i=h(h({},i),{},{tickCoord:f<0?i.coordinate-f*t:i.coordinate})}else a[e]=i=h(h({},i),{},{tickCoord:i.coordinate});s(t,i.tickCoord,u,c,l)&&(c=i.tickCoord+t*(u()/2+o),a[e]=h(h({},i),{},{isShow:!0}))},m=0;m0?l.coordinate-p*t:l.coordinate})}else i[e]=l=h(h({},l),{},{tickCoord:l.coordinate});s(t,l.tickCoord,f,u,c)&&(c=l.tickCoord-t*(f()/2+o),i[e]=h(h({},l),{},{isShow:!0}))},f=a-1;f>=0;f--)l(f);return i}(A,M,k,m,g)).filter(function(t){return t.isShow})}},93765:function(t,e,r){"use strict";r.d(e,{z:function(){return eD}});var n,o,i=r(2265),a=r(77571),u=r.n(a),c=r(86757),l=r.n(c),s=r(99676),f=r.n(s),p=r(13735),h=r.n(p),d=r(34935),y=r.n(d),v=r(37065),m=r.n(v),b=r(61994),g=r(69398),x=r(48777),w=r(9841),O=r(8147),j=r(22190),S=r(81889),P=r(73649),E=r(82944),k=r(55284),A=r(58811),M=r(85355),_=r(16630);function T(t){return(T="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function C(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function N(t){for(var e=1;e0&&e.handleDrag(t.changedTouches[0])}),W(e,"handleDragEnd",function(){e.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var t=e.props,r=t.endIndex,n=t.onDragEnd,o=t.startIndex;null==n||n({endIndex:r,startIndex:o})}),e.detachDragEndListener()}),W(e,"handleLeaveWrapper",function(){(e.state.isTravellerMoving||e.state.isSlideMoving)&&(e.leaveTimer=window.setTimeout(e.handleDragEnd,e.props.leaveTimeOut))}),W(e,"handleEnterSlideOrTraveller",function(){e.setState({isTextActive:!0})}),W(e,"handleLeaveSlideOrTraveller",function(){e.setState({isTextActive:!1})}),W(e,"handleSlideDragStart",function(t){var r=X(t)?t.changedTouches[0]:t;e.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:r.pageX}),e.attachDragEndListener()}),e.travellerDragStartHandlers={startX:e.handleTravellerDragStart.bind(e,"startX"),endX:e.handleTravellerDragStart.bind(e,"endX")},e.state={},e}return!function(t,e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Z(t,e)}(n,t),e=[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(t){var e=t.startX,r=t.endX,o=this.state.scaleValues,i=this.props,a=i.gap,u=i.data.length-1,c=n.getIndexInRange(o,Math.min(e,r)),l=n.getIndexInRange(o,Math.max(e,r));return{startIndex:c-c%a,endIndex:l===u?u:l-l%a}}},{key:"getTextOfTick",value:function(t){var e=this.props,r=e.data,n=e.tickFormatter,o=e.dataKey,i=(0,M.F$)(r[t],o,t);return l()(n)?n(i,t):i}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(t){var e=this.state,r=e.slideMoveStartX,n=e.startX,o=e.endX,i=this.props,a=i.x,u=i.width,c=i.travellerWidth,l=i.startIndex,s=i.endIndex,f=i.onChange,p=t.pageX-r;p>0?p=Math.min(p,a+u-c-o,a+u-c-n):p<0&&(p=Math.max(p,a-n,a-o));var h=this.getIndex({startX:n+p,endX:o+p});(h.startIndex!==l||h.endIndex!==s)&&f&&f(h),this.setState({startX:n+p,endX:o+p,slideMoveStartX:t.pageX})}},{key:"handleTravellerDragStart",value:function(t,e){var r=X(e)?e.changedTouches[0]:e;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:t,brushMoveStartX:r.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(t){var e=this.state,r=e.brushMoveStartX,n=e.movingTravellerId,o=e.endX,i=e.startX,a=this.state[n],u=this.props,c=u.x,l=u.width,s=u.travellerWidth,f=u.onChange,p=u.gap,h=u.data,d={startX:this.state.startX,endX:this.state.endX},y=t.pageX-r;y>0?y=Math.min(y,c+l-s-a):y<0&&(y=Math.max(y,c-a)),d[n]=a+y;var v=this.getIndex(d),m=v.startIndex,b=v.endIndex,g=function(){var t=h.length-1;return"startX"===n&&(o>i?m%p==0:b%p==0)||oi?b%p==0:m%p==0)||o>i&&b===t};this.setState(W(W({},n,a+y),"brushMoveStartX",t.pageX),function(){f&&g()&&f(v)})}},{key:"handleTravellerMoveKeyboard",value:function(t,e){var r=this,n=this.state,o=n.scaleValues,i=n.startX,a=n.endX,u=this.state[e],c=o.indexOf(u);if(-1!==c){var l=c+t;if(-1!==l&&!(l>=o.length)){var s=o[l];"startX"===e&&s>=a||"endX"===e&&s<=i||this.setState(W({},e,s),function(){r.props.onChange(r.getIndex({startX:r.state.startX,endX:r.state.endX}))})}}}},{key:"renderBackground",value:function(){var t=this.props,e=t.x,r=t.y,n=t.width,o=t.height,a=t.fill,u=t.stroke;return i.createElement("rect",{stroke:u,fill:a,x:e,y:r,width:n,height:o})}},{key:"renderPanorama",value:function(){var t=this.props,e=t.x,r=t.y,n=t.width,o=t.height,a=t.data,u=t.children,c=t.padding,l=i.Children.only(u);return l?i.cloneElement(l,{x:e,y:r,width:n,height:o,margin:c,compact:!0,data:a}):null}},{key:"renderTravellerLayer",value:function(t,e){var r,o,a=this,u=this.props,c=u.y,l=u.travellerWidth,s=u.height,f=u.traveller,p=u.ariaLabel,h=u.data,d=u.startIndex,y=u.endIndex,v=Math.max(t,this.props.x),m=U(U({},(0,E.L6)(this.props,!1)),{},{x:v,y:c,width:l,height:s}),b=p||"Min value: ".concat(null===(r=h[d])||void 0===r?void 0:r.name,", Max value: ").concat(null===(o=h[y])||void 0===o?void 0:o.name);return i.createElement(w.m,{tabIndex:0,role:"slider","aria-label":b,"aria-valuenow":t,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[e],onTouchStart:this.travellerDragStartHandlers[e],onKeyDown:function(t){["ArrowLeft","ArrowRight"].includes(t.key)&&(t.preventDefault(),t.stopPropagation(),a.handleTravellerMoveKeyboard("ArrowRight"===t.key?1:-1,e))},onFocus:function(){a.setState({isTravellerFocused:!0})},onBlur:function(){a.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},n.renderTraveller(f,m))}},{key:"renderSlide",value:function(t,e){var r=this.props,n=r.y,o=r.height,a=r.stroke,u=r.travellerWidth;return i.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:a,fillOpacity:.2,x:Math.min(t,e)+u,y:n,width:Math.max(Math.abs(e-t)-u,0),height:o})}},{key:"renderText",value:function(){var t=this.props,e=t.startIndex,r=t.endIndex,n=t.y,o=t.height,a=t.travellerWidth,u=t.stroke,c=this.state,l=c.startX,s=c.endX,f={pointerEvents:"none",fill:u};return i.createElement(w.m,{className:"recharts-brush-texts"},i.createElement(A.x,R({textAnchor:"end",verticalAnchor:"middle",x:Math.min(l,s)-5,y:n+o/2},f),this.getTextOfTick(e)),i.createElement(A.x,R({textAnchor:"start",verticalAnchor:"middle",x:Math.max(l,s)+a+5,y:n+o/2},f),this.getTextOfTick(r)))}},{key:"render",value:function(){var t=this.props,e=t.data,r=t.className,n=t.children,o=t.x,a=t.y,u=t.width,c=t.height,l=t.alwaysShowText,s=this.state,f=s.startX,p=s.endX,h=s.isTextActive,d=s.isSlideMoving,y=s.isTravellerMoving,v=s.isTravellerFocused;if(!e||!e.length||!(0,_.hj)(o)||!(0,_.hj)(a)||!(0,_.hj)(u)||!(0,_.hj)(c)||u<=0||c<=0)return null;var m=(0,b.Z)("recharts-brush",r),g=1===i.Children.count(n),x=L("userSelect","none");return i.createElement(w.m,{className:m,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:x},this.renderBackground(),g&&this.renderPanorama(),this.renderSlide(f,p),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(p,"endX"),(h||d||y||v||l)&&this.renderText())}}],r=[{key:"renderDefaultTraveller",value:function(t){var e=t.x,r=t.y,n=t.width,o=t.height,a=t.stroke,u=Math.floor(r+o/2)-1;return i.createElement(i.Fragment,null,i.createElement("rect",{x:e,y:r,width:n,height:o,fill:a,stroke:"none"}),i.createElement("line",{x1:e+1,y1:u,x2:e+n-1,y2:u,fill:"none",stroke:"#fff"}),i.createElement("line",{x1:e+1,y1:u+2,x2:e+n-1,y2:u+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(t,e){return i.isValidElement(t)?i.cloneElement(t,e):l()(t)?t(e):n.renderDefaultTraveller(e)}},{key:"getDerivedStateFromProps",value:function(t,e){var r=t.data,n=t.width,o=t.x,i=t.travellerWidth,a=t.updateId,u=t.startIndex,c=t.endIndex;if(r!==e.prevData||a!==e.prevUpdateId)return U({prevData:r,prevTravellerWidth:i,prevUpdateId:a,prevX:o,prevWidth:n},r&&r.length?H({data:r,width:n,x:o,travellerWidth:i,startIndex:u,endIndex:c}):{scale:null,scaleValues:null});if(e.scale&&(n!==e.prevWidth||o!==e.prevX||i!==e.prevTravellerWidth)){e.scale.range([o,o+n-i]);var l=e.scale.domain().map(function(t){return e.scale(t)});return{prevData:r,prevTravellerWidth:i,prevUpdateId:a,prevX:o,prevWidth:n,startX:e.scale(t.startIndex),endX:e.scale(t.endIndex),scaleValues:l}}return null}},{key:"getIndexInRange",value:function(t,e){for(var r=t.length,n=0,o=r-1;o-n>1;){var i=Math.floor((n+o)/2);t[i]>e?o=i:n=i}return e>=t[o]?o:n}}],e&&F(n.prototype,e),r&&F(n,r),Object.defineProperty(n,"prototype",{writable:!1}),n}(i.PureComponent);W(G,"displayName","Brush"),W(G,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var V=r(4094),K=r(38569),Q=r(26680),J=function(t,e){var r=t.alwaysShow,n=t.ifOverflow;return r&&(n="extendDomain"),n===e},tt=r(25311),te=r(1175);function tr(){return(tr=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);rt.length)&&(e=t.length);for(var r=0,n=Array(e);r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,t2));return(0,_.hj)(r)&&(0,_.hj)(o)&&(0,_.hj)(f)&&(0,_.hj)(h)&&(0,_.hj)(u)&&(0,_.hj)(l)?i.createElement("path",t5({},(0,E.L6)(y,!0),{className:(0,b.Z)("recharts-cross",d),d:"M".concat(r,",").concat(u,"v").concat(h,"M").concat(l,",").concat(o,"h").concat(f)})):null};function t7(t){var e=t.cx,r=t.cy,n=t.radius,o=t.startAngle,i=t.endAngle;return{points:[(0,tq.op)(e,r,n,o),(0,tq.op)(e,r,n,i)],cx:e,cy:r,radius:n,startAngle:o,endAngle:i}}var t4=r(60474);function t8(t){return(t8="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function t9(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function et(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function ec(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(ec=function(){return!!t})()}function el(t){return(el=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function es(t,e){return(es=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function ef(t){return function(t){if(Array.isArray(t))return eh(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||ep(t)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function ep(t,e){if(t){if("string"==typeof t)return eh(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return eh(t,e)}}function eh(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r0?i:t&&t.length&&(0,_.hj)(n)&&(0,_.hj)(o)?t.slice(n,o+1):[]};function eS(t){return"number"===t?[0,"auto"]:void 0}var eP=function(t,e,r,n){var o=t.graphicalItems,i=t.tooltipAxis,a=ej(e,t);return r<0||!o||!o.length||r>=a.length?null:o.reduce(function(o,u){var c,l,s=null!==(c=u.props.data)&&void 0!==c?c:e;if(s&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(s=s.slice(t.dataStartIndex,t.dataEndIndex+1)),i.dataKey&&!i.allowDuplicatedCategory){var f=void 0===s?a:s;l=(0,_.Ap)(f,i.dataKey,n)}else l=s&&s[r]||a[r];return l?[].concat(ef(o),[(0,M.Qo)(u,l)]):o},[])},eE=function(t,e,r,n){var o=n||{x:t.chartX,y:t.chartY},i="horizontal"===r?o.x:"vertical"===r?o.y:"centric"===r?o.angle:o.radius,a=t.orderedTooltipTicks,u=t.tooltipAxis,c=t.tooltipTicks,l=(0,M.VO)(i,a,c,u);if(l>=0&&c){var s=c[l]&&c[l].value,f=eP(t,e,l,s),p=eO(r,a,l,o);return{activeTooltipIndex:l,activeLabel:s,activePayload:f,activeCoordinate:p}}return null},ek=function(t,e){var r=e.axes,n=e.graphicalItems,o=e.axisType,i=e.axisIdKey,a=e.stackGroups,c=e.dataStartIndex,l=e.dataEndIndex,s=t.layout,p=t.children,h=t.stackOffset,d=(0,M.NA)(s,o);return r.reduce(function(e,r){var y=void 0!==r.type.defaultProps?ey(ey({},r.type.defaultProps),r.props):r.props,v=y.type,m=y.dataKey,b=y.allowDataOverflow,g=y.allowDuplicatedCategory,x=y.scale,w=y.ticks,O=y.includeHidden,j=y[i];if(e[j])return e;var S=ej(t.data,{graphicalItems:n.filter(function(t){var e;return(i in t.props?t.props[i]:null===(e=t.type.defaultProps)||void 0===e?void 0:e[i])===j}),dataStartIndex:c,dataEndIndex:l}),P=S.length;(function(t,e,r){if("number"===r&&!0===e&&Array.isArray(t)){var n=null==t?void 0:t[0],o=null==t?void 0:t[1];if(n&&o&&(0,_.hj)(n)&&(0,_.hj)(o))return!0}return!1})(y.domain,b,v)&&(A=(0,M.LG)(y.domain,null,b),d&&("number"===v||"auto"!==x)&&(C=(0,M.gF)(S,m,"category")));var E=eS(v);if(!A||0===A.length){var k,A,T,C,N,D=null!==(N=y.domain)&&void 0!==N?N:E;if(m){if(A=(0,M.gF)(S,m,v),"category"===v&&d){var I=(0,_.bv)(A);g&&I?(T=A,A=f()(0,P)):g||(A=(0,M.ko)(D,A,r).reduce(function(t,e){return t.indexOf(e)>=0?t:[].concat(ef(t),[e])},[]))}else if("category"===v)A=g?A.filter(function(t){return""!==t&&!u()(t)}):(0,M.ko)(D,A,r).reduce(function(t,e){return t.indexOf(e)>=0||""===e||u()(e)?t:[].concat(ef(t),[e])},[]);else if("number"===v){var L=(0,M.ZI)(S,n.filter(function(t){var e,r,n=i in t.props?t.props[i]:null===(e=t.type.defaultProps)||void 0===e?void 0:e[i],o="hide"in t.props?t.props.hide:null===(r=t.type.defaultProps)||void 0===r?void 0:r.hide;return n===j&&(O||!o)}),m,o,s);L&&(A=L)}d&&("number"===v||"auto"!==x)&&(C=(0,M.gF)(S,m,"category"))}else A=d?f()(0,P):a&&a[j]&&a[j].hasStack&&"number"===v?"expand"===h?[0,1]:(0,M.EB)(a[j].stackGroups,c,l):(0,M.s6)(S,n.filter(function(t){var e=i in t.props?t.props[i]:t.type.defaultProps[i],r="hide"in t.props?t.props.hide:t.type.defaultProps.hide;return e===j&&(O||!r)}),v,s,!0);"number"===v?(A=t$(p,A,j,o,w),D&&(A=(0,M.LG)(D,A,b))):"category"===v&&D&&A.every(function(t){return D.indexOf(t)>=0})&&(A=D)}return ey(ey({},e),{},ev({},j,ey(ey({},y),{},{axisType:o,domain:A,categoricalDomain:C,duplicateDomain:T,originalDomain:null!==(k=y.domain)&&void 0!==k?k:E,isCategorical:d,layout:s})))},{})},eA=function(t,e){var r=e.graphicalItems,n=e.Axis,o=e.axisType,i=e.axisIdKey,a=e.stackGroups,u=e.dataStartIndex,c=e.dataEndIndex,l=t.layout,s=t.children,p=ej(t.data,{graphicalItems:r,dataStartIndex:u,dataEndIndex:c}),d=p.length,y=(0,M.NA)(l,o),v=-1;return r.reduce(function(t,e){var m,b=(void 0!==e.type.defaultProps?ey(ey({},e.type.defaultProps),e.props):e.props)[i],g=eS("number");return t[b]?t:(v++,m=y?f()(0,d):a&&a[b]&&a[b].hasStack?t$(s,m=(0,M.EB)(a[b].stackGroups,u,c),b,o):t$(s,m=(0,M.LG)(g,(0,M.s6)(p,r.filter(function(t){var e,r,n=i in t.props?t.props[i]:null===(e=t.type.defaultProps)||void 0===e?void 0:e[i],o="hide"in t.props?t.props.hide:null===(r=t.type.defaultProps)||void 0===r?void 0:r.hide;return n===b&&!o}),"number",l),n.defaultProps.allowDataOverflow),b,o),ey(ey({},t),{},ev({},b,ey(ey({axisType:o},n.defaultProps),{},{hide:!0,orientation:h()(eb,"".concat(o,".").concat(v%2),null),domain:m,originalDomain:g,isCategorical:y,layout:l}))))},{})},eM=function(t,e){var r=e.axisType,n=void 0===r?"xAxis":r,o=e.AxisComp,i=e.graphicalItems,a=e.stackGroups,u=e.dataStartIndex,c=e.dataEndIndex,l=t.children,s="".concat(n,"Id"),f=(0,E.NN)(l,o),p={};return f&&f.length?p=ek(t,{axes:f,graphicalItems:i,axisType:n,axisIdKey:s,stackGroups:a,dataStartIndex:u,dataEndIndex:c}):i&&i.length&&(p=eA(t,{Axis:o,graphicalItems:i,axisType:n,axisIdKey:s,stackGroups:a,dataStartIndex:u,dataEndIndex:c})),p},e_=function(t){var e=(0,_.Kt)(t),r=(0,M.uY)(e,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:y()(r,function(t){return t.coordinate}),tooltipAxis:e,tooltipAxisBandSize:(0,M.zT)(e,r)}},eT=function(t){var e=t.children,r=t.defaultShowTooltip,n=(0,E.sP)(e,G),o=0,i=0;return t.data&&0!==t.data.length&&(i=t.data.length-1),n&&n.props&&(n.props.startIndex>=0&&(o=n.props.startIndex),n.props.endIndex>=0&&(i=n.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:o,dataEndIndex:i,activeTooltipIndex:-1,isTooltipActive:!!r}},eC=function(t){return"horizontal"===t?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:"vertical"===t?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:"centric"===t?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},eN=function(t,e){var r=t.props,n=t.graphicalItems,o=t.xAxisMap,i=void 0===o?{}:o,a=t.yAxisMap,u=void 0===a?{}:a,c=r.width,l=r.height,s=r.children,f=r.margin||{},p=(0,E.sP)(s,G),d=(0,E.sP)(s,j.D),y=Object.keys(u).reduce(function(t,e){var r=u[e],n=r.orientation;return r.mirror||r.hide?t:ey(ey({},t),{},ev({},n,t[n]+r.width))},{left:f.left||0,right:f.right||0}),v=Object.keys(i).reduce(function(t,e){var r=i[e],n=r.orientation;return r.mirror||r.hide?t:ey(ey({},t),{},ev({},n,h()(t,"".concat(n))+r.height))},{top:f.top||0,bottom:f.bottom||0}),m=ey(ey({},v),y),b=m.bottom;p&&(m.bottom+=p.props.height||G.defaultProps.height),d&&e&&(m=(0,M.By)(m,n,r,e));var g=c-m.left-m.right,x=l-m.top-m.bottom;return ey(ey({brushBottom:b},m),{},{width:Math.max(g,0),height:Math.max(x,0)})},eD=function(t){var e=t.chartName,r=t.GraphicalChild,n=t.defaultTooltipEventType,o=void 0===n?"axis":n,a=t.validateTooltipEventTypes,c=void 0===a?["axis"]:a,s=t.axisComponents,f=t.legendContent,p=t.formatAxisMap,d=t.defaultProps,y=function(t,e){var r=e.graphicalItems,n=e.stackGroups,o=e.offset,i=e.updateId,a=e.dataStartIndex,c=e.dataEndIndex,l=t.barSize,f=t.layout,p=t.barGap,h=t.barCategoryGap,d=t.maxBarSize,y=eC(f),v=y.numericAxisName,m=y.cateAxisName,b=!!r&&!!r.length&&r.some(function(t){var e=(0,E.Gf)(t&&t.type);return e&&e.indexOf("Bar")>=0}),x=[];return r.forEach(function(r,y){var w=ej(t.data,{graphicalItems:[r],dataStartIndex:a,dataEndIndex:c}),O=void 0!==r.type.defaultProps?ey(ey({},r.type.defaultProps),r.props):r.props,j=O.dataKey,S=O.maxBarSize,P=O["".concat(v,"Id")],k=O["".concat(m,"Id")],A=s.reduce(function(t,r){var n=e["".concat(r.axisType,"Map")],o=O["".concat(r.axisType,"Id")];n&&n[o]||"zAxis"===r.axisType||(0,g.Z)(!1);var i=n[o];return ey(ey({},t),{},ev(ev({},r.axisType,i),"".concat(r.axisType,"Ticks"),(0,M.uY)(i)))},{}),_=A[m],T=A["".concat(m,"Ticks")],C=n&&n[P]&&n[P].hasStack&&(0,M.O3)(r,n[P].stackGroups),N=(0,E.Gf)(r.type).indexOf("Bar")>=0,D=(0,M.zT)(_,T),I=[],L=b&&(0,M.pt)({barSize:l,stackGroups:n,totalSize:"xAxis"===m?A[m].width:"yAxis"===m?A[m].height:void 0});if(N){var B,R,z=u()(S)?d:S,U=null!==(B=null!==(R=(0,M.zT)(_,T,!0))&&void 0!==R?R:z)&&void 0!==B?B:0;I=(0,M.qz)({barGap:p,barCategoryGap:h,bandSize:U!==D?U:D,sizeList:L[k],maxBarSize:z}),U!==D&&(I=I.map(function(t){return ey(ey({},t),{},{position:ey(ey({},t.position),{},{offset:t.position.offset-U/2})})}))}var F=r&&r.type&&r.type.getComposedData;F&&x.push({props:ey(ey({},F(ey(ey({},A),{},{displayedData:w,props:t,dataKey:j,item:r,bandSize:D,barPosition:I,offset:o,stackedData:C,layout:f,dataStartIndex:a,dataEndIndex:c}))),{},ev(ev(ev({key:r.key||"item-".concat(y)},v,A[v]),m,A[m]),"animationId",i)),childIndex:(0,E.$R)(r,t.children),item:r})}),x},v=function(t,n){var o=t.props,i=t.dataStartIndex,a=t.dataEndIndex,u=t.updateId;if(!(0,E.TT)({props:o}))return null;var c=o.children,l=o.layout,f=o.stackOffset,h=o.data,d=o.reverseStackOrder,v=eC(l),m=v.numericAxisName,b=v.cateAxisName,g=(0,E.NN)(c,r),x=(0,M.wh)(h,g,"".concat(m,"Id"),"".concat(b,"Id"),f,d),w=s.reduce(function(t,e){var r="".concat(e.axisType,"Map");return ey(ey({},t),{},ev({},r,eM(o,ey(ey({},e),{},{graphicalItems:g,stackGroups:e.axisType===m&&x,dataStartIndex:i,dataEndIndex:a}))))},{}),O=eN(ey(ey({},w),{},{props:o,graphicalItems:g}),null==n?void 0:n.legendBBox);Object.keys(w).forEach(function(t){w[t]=p(o,w[t],O,t.replace("Map",""),e)});var j=e_(w["".concat(b,"Map")]),S=y(o,ey(ey({},w),{},{dataStartIndex:i,dataEndIndex:a,updateId:u,graphicalItems:g,stackGroups:x,offset:O}));return ey(ey({formattedGraphicalItems:S,graphicalItems:g,offset:O,stackGroups:x},j),w)},j=function(t){var r;function n(t){var r,o,a,c,s;return!function(t,e){if(!(t instanceof e))throw TypeError("Cannot call a class as a function")}(this,n),c=n,s=[t],c=el(c),ev(a=function(t,e){if(e&&("object"===eo(e)||"function"==typeof e))return e;if(void 0!==e)throw TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(this,ec()?Reflect.construct(c,s||[],el(this).constructor):c.apply(this,s)),"eventEmitterSymbol",Symbol("rechartsEventEmitter")),ev(a,"accessibilityManager",new tQ),ev(a,"handleLegendBBoxUpdate",function(t){if(t){var e=a.state,r=e.dataStartIndex,n=e.dataEndIndex,o=e.updateId;a.setState(ey({legendBBox:t},v({props:a.props,dataStartIndex:r,dataEndIndex:n,updateId:o},ey(ey({},a.state),{},{legendBBox:t}))))}}),ev(a,"handleReceiveSyncEvent",function(t,e,r){a.props.syncId===t&&(r!==a.eventEmitterSymbol||"function"==typeof a.props.syncMethod)&&a.applySyncEvent(e)}),ev(a,"handleBrushChange",function(t){var e=t.startIndex,r=t.endIndex;if(e!==a.state.dataStartIndex||r!==a.state.dataEndIndex){var n=a.state.updateId;a.setState(function(){return ey({dataStartIndex:e,dataEndIndex:r},v({props:a.props,dataStartIndex:e,dataEndIndex:r,updateId:n},a.state))}),a.triggerSyncEvent({dataStartIndex:e,dataEndIndex:r})}}),ev(a,"handleMouseEnter",function(t){var e=a.getMouseInfo(t);if(e){var r=ey(ey({},e),{},{isTooltipActive:!0});a.setState(r),a.triggerSyncEvent(r);var n=a.props.onMouseEnter;l()(n)&&n(r,t)}}),ev(a,"triggeredAfterMouseMove",function(t){var e=a.getMouseInfo(t),r=e?ey(ey({},e),{},{isTooltipActive:!0}):{isTooltipActive:!1};a.setState(r),a.triggerSyncEvent(r);var n=a.props.onMouseMove;l()(n)&&n(r,t)}),ev(a,"handleItemMouseEnter",function(t){a.setState(function(){return{isTooltipActive:!0,activeItem:t,activePayload:t.tooltipPayload,activeCoordinate:t.tooltipPosition||{x:t.cx,y:t.cy}}})}),ev(a,"handleItemMouseLeave",function(){a.setState(function(){return{isTooltipActive:!1}})}),ev(a,"handleMouseMove",function(t){t.persist(),a.throttleTriggeredAfterMouseMove(t)}),ev(a,"handleMouseLeave",function(t){a.throttleTriggeredAfterMouseMove.cancel();var e={isTooltipActive:!1};a.setState(e),a.triggerSyncEvent(e);var r=a.props.onMouseLeave;l()(r)&&r(e,t)}),ev(a,"handleOuterEvent",function(t){var e,r=(0,E.Bh)(t),n=h()(a.props,"".concat(r));r&&l()(n)&&n(null!==(e=/.*touch.*/i.test(r)?a.getMouseInfo(t.changedTouches[0]):a.getMouseInfo(t))&&void 0!==e?e:{},t)}),ev(a,"handleClick",function(t){var e=a.getMouseInfo(t);if(e){var r=ey(ey({},e),{},{isTooltipActive:!0});a.setState(r),a.triggerSyncEvent(r);var n=a.props.onClick;l()(n)&&n(r,t)}}),ev(a,"handleMouseDown",function(t){var e=a.props.onMouseDown;l()(e)&&e(a.getMouseInfo(t),t)}),ev(a,"handleMouseUp",function(t){var e=a.props.onMouseUp;l()(e)&&e(a.getMouseInfo(t),t)}),ev(a,"handleTouchMove",function(t){null!=t.changedTouches&&t.changedTouches.length>0&&a.throttleTriggeredAfterMouseMove(t.changedTouches[0])}),ev(a,"handleTouchStart",function(t){null!=t.changedTouches&&t.changedTouches.length>0&&a.handleMouseDown(t.changedTouches[0])}),ev(a,"handleTouchEnd",function(t){null!=t.changedTouches&&t.changedTouches.length>0&&a.handleMouseUp(t.changedTouches[0])}),ev(a,"handleDoubleClick",function(t){var e=a.props.onDoubleClick;l()(e)&&e(a.getMouseInfo(t),t)}),ev(a,"handleContextMenu",function(t){var e=a.props.onContextMenu;l()(e)&&e(a.getMouseInfo(t),t)}),ev(a,"triggerSyncEvent",function(t){void 0!==a.props.syncId&&tY.emit(tH,a.props.syncId,t,a.eventEmitterSymbol)}),ev(a,"applySyncEvent",function(t){var e=a.props,r=e.layout,n=e.syncMethod,o=a.state.updateId,i=t.dataStartIndex,u=t.dataEndIndex;if(void 0!==t.dataStartIndex||void 0!==t.dataEndIndex)a.setState(ey({dataStartIndex:i,dataEndIndex:u},v({props:a.props,dataStartIndex:i,dataEndIndex:u,updateId:o},a.state)));else if(void 0!==t.activeTooltipIndex){var c=t.chartX,l=t.chartY,s=t.activeTooltipIndex,f=a.state,p=f.offset,h=f.tooltipTicks;if(!p)return;if("function"==typeof n)s=n(h,t);else if("value"===n){s=-1;for(var d=0;d=0){if(s.dataKey&&!s.allowDuplicatedCategory){var A="function"==typeof s.dataKey?function(t){return"function"==typeof s.dataKey?s.dataKey(t.payload):null}:"payload.".concat(s.dataKey.toString());C=(0,_.Ap)(v,A,p),N=m&&b&&(0,_.Ap)(b,A,p)}else C=null==v?void 0:v[f],N=m&&b&&b[f];if(S||j){var T=void 0!==t.props.activeIndex?t.props.activeIndex:f;return[(0,i.cloneElement)(t,ey(ey(ey({},n.props),P),{},{activeIndex:T})),null,null]}if(!u()(C))return[k].concat(ef(a.renderActivePoints({item:n,activePoint:C,basePoint:N,childIndex:f,isRange:m})))}else{var C,N,D,I=(null!==(D=a.getItemByXY(a.state.activeCoordinate))&&void 0!==D?D:{graphicalItem:k}).graphicalItem,L=I.item,B=void 0===L?t:L,R=I.childIndex,z=ey(ey(ey({},n.props),P),{},{activeIndex:R});return[(0,i.cloneElement)(B,z),null,null]}}return m?[k,null,null]:[k,null]}),ev(a,"renderCustomized",function(t,e,r){return(0,i.cloneElement)(t,ey(ey({key:"recharts-customized-".concat(r)},a.props),a.state))}),ev(a,"renderMap",{CartesianGrid:{handler:ew,once:!0},ReferenceArea:{handler:a.renderReferenceElement},ReferenceLine:{handler:ew},ReferenceDot:{handler:a.renderReferenceElement},XAxis:{handler:ew},YAxis:{handler:ew},Brush:{handler:a.renderBrush,once:!0},Bar:{handler:a.renderGraphicChild},Line:{handler:a.renderGraphicChild},Area:{handler:a.renderGraphicChild},Radar:{handler:a.renderGraphicChild},RadialBar:{handler:a.renderGraphicChild},Scatter:{handler:a.renderGraphicChild},Pie:{handler:a.renderGraphicChild},Funnel:{handler:a.renderGraphicChild},Tooltip:{handler:a.renderCursor,once:!0},PolarGrid:{handler:a.renderPolarGrid,once:!0},PolarAngleAxis:{handler:a.renderPolarAxis},PolarRadiusAxis:{handler:a.renderPolarAxis},Customized:{handler:a.renderCustomized}}),a.clipPathId="".concat(null!==(r=t.id)&&void 0!==r?r:(0,_.EL)("recharts"),"-clip"),a.throttleTriggeredAfterMouseMove=m()(a.triggeredAfterMouseMove,null!==(o=t.throttleDelay)&&void 0!==o?o:1e3/60),a.state={},a}return!function(t,e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&es(t,e)}(n,t),r=[{key:"componentDidMount",value:function(){var t,e;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:null!==(t=this.props.margin.left)&&void 0!==t?t:0,top:null!==(e=this.props.margin.top)&&void 0!==e?e:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var t=this.props,e=t.children,r=t.data,n=t.height,o=t.layout,i=(0,E.sP)(e,O.u);if(i){var a=i.props.defaultIndex;if("number"==typeof a&&!(a<0)&&!(a>this.state.tooltipTicks.length-1)){var u=this.state.tooltipTicks[a]&&this.state.tooltipTicks[a].value,c=eP(this.state,r,a,u),l=this.state.tooltipTicks[a].coordinate,s=(this.state.offset.top+n)/2,f="horizontal"===o?{x:l,y:s}:{y:l,x:s},p=this.state.formattedGraphicalItems.find(function(t){return"Scatter"===t.item.type.name});p&&(f=ey(ey({},f),p.props.points[a].tooltipPosition),c=p.props.points[a].tooltipPayload);var h={activeTooltipIndex:a,isTooltipActive:!0,activeLabel:u,activePayload:c,activeCoordinate:f};this.setState(h),this.renderCursor(i),this.accessibilityManager.setIndex(a)}}}},{key:"getSnapshotBeforeUpdate",value:function(t,e){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==e.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==t.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==t.margin){var r,n;this.accessibilityManager.setDetails({offset:{left:null!==(r=this.props.margin.left)&&void 0!==r?r:0,top:null!==(n=this.props.margin.top)&&void 0!==n?n:0}})}return null}},{key:"componentDidUpdate",value:function(t){(0,E.rL)([(0,E.sP)(t.children,O.u)],[(0,E.sP)(this.props.children,O.u)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var t=(0,E.sP)(this.props.children,O.u);if(t&&"boolean"==typeof t.props.shared){var e=t.props.shared?"axis":"item";return c.indexOf(e)>=0?e:o}return o}},{key:"getMouseInfo",value:function(t){if(!this.container)return null;var e=this.container,r=e.getBoundingClientRect(),n=(0,V.os)(r),o={chartX:Math.round(t.pageX-n.left),chartY:Math.round(t.pageY-n.top)},i=r.width/e.offsetWidth||1,a=this.inRange(o.chartX,o.chartY,i);if(!a)return null;var u=this.state,c=u.xAxisMap,l=u.yAxisMap,s=this.getTooltipEventType(),f=eE(this.state,this.props.data,this.props.layout,a);if("axis"!==s&&c&&l){var p=(0,_.Kt)(c).scale,h=(0,_.Kt)(l).scale,d=p&&p.invert?p.invert(o.chartX):null,y=h&&h.invert?h.invert(o.chartY):null;return ey(ey({},o),{},{xValue:d,yValue:y},f)}return f?ey(ey({},o),f):null}},{key:"inRange",value:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=this.props.layout,o=t/r,i=e/r;if("horizontal"===n||"vertical"===n){var a=this.state.offset;return o>=a.left&&o<=a.left+a.width&&i>=a.top&&i<=a.top+a.height?{x:o,y:i}:null}var u=this.state,c=u.angleAxisMap,l=u.radiusAxisMap;if(c&&l){var s=(0,_.Kt)(c);return(0,tq.z3)({x:o,y:i},s)}return null}},{key:"parseEventsOfWrapper",value:function(){var t=this.props.children,e=this.getTooltipEventType(),r=(0,E.sP)(t,O.u),n={};return r&&"axis"===e&&(n="click"===r.props.trigger?{onClick:this.handleClick}:{onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu}),ey(ey({},(0,tX.Ym)(this.props,this.handleOuterEvent)),n)}},{key:"addListener",value:function(){tY.on(tH,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){tY.removeListener(tH,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(t,e,r){for(var n=this.state.formattedGraphicalItems,o=0,i=n.length;ot.length)&&(e=t.length);for(var r=0,n=Array(e);r=0?1:-1;"insideStart"===u?(o=b+S*l,a=w):"insideEnd"===u?(o=g-S*l,a=!w):"end"===u&&(o=g+S*l,a=w),a=j<=0?a:!a;var P=(0,d.op)(p,y,O,o),E=(0,d.op)(p,y,O,o+(a?1:-1)*359),k="M".concat(P.x,",").concat(P.y,"\n A").concat(O,",").concat(O,",0,1,").concat(a?0:1,",\n ").concat(E.x,",").concat(E.y),A=i()(t.id)?(0,h.EL)("recharts-radial-line-"):t.id;return n.createElement("text",x({},r,{dominantBaseline:"central",className:(0,s.Z)("recharts-radial-bar-label",f)}),n.createElement("defs",null,n.createElement("path",{id:A,d:k})),n.createElement("textPath",{xlinkHref:"#".concat(A)},e))},j=function(t){var e=t.viewBox,r=t.offset,n=t.position,o=e.cx,i=e.cy,a=e.innerRadius,u=e.outerRadius,c=(e.startAngle+e.endAngle)/2;if("outside"===n){var l=(0,d.op)(o,i,u+r,c),s=l.x;return{x:s,y:l.y,textAnchor:s>=o?"start":"end",verticalAnchor:"middle"}}if("center"===n)return{x:o,y:i,textAnchor:"middle",verticalAnchor:"middle"};if("centerTop"===n)return{x:o,y:i,textAnchor:"middle",verticalAnchor:"start"};if("centerBottom"===n)return{x:o,y:i,textAnchor:"middle",verticalAnchor:"end"};var f=(0,d.op)(o,i,(a+u)/2,c);return{x:f.x,y:f.y,textAnchor:"middle",verticalAnchor:"middle"}},S=function(t){var e=t.viewBox,r=t.parentViewBox,n=t.offset,o=t.position,i=e.x,a=e.y,u=e.width,c=e.height,s=c>=0?1:-1,f=s*n,p=s>0?"end":"start",d=s>0?"start":"end",y=u>=0?1:-1,v=y*n,m=y>0?"end":"start",b=y>0?"start":"end";if("top"===o)return g(g({},{x:i+u/2,y:a-s*n,textAnchor:"middle",verticalAnchor:p}),r?{height:Math.max(a-r.y,0),width:u}:{});if("bottom"===o)return g(g({},{x:i+u/2,y:a+c+f,textAnchor:"middle",verticalAnchor:d}),r?{height:Math.max(r.y+r.height-(a+c),0),width:u}:{});if("left"===o){var x={x:i-v,y:a+c/2,textAnchor:m,verticalAnchor:"middle"};return g(g({},x),r?{width:Math.max(x.x-r.x,0),height:c}:{})}if("right"===o){var w={x:i+u+v,y:a+c/2,textAnchor:b,verticalAnchor:"middle"};return g(g({},w),r?{width:Math.max(r.x+r.width-w.x,0),height:c}:{})}var O=r?{width:u,height:c}:{};return"insideLeft"===o?g({x:i+v,y:a+c/2,textAnchor:b,verticalAnchor:"middle"},O):"insideRight"===o?g({x:i+u-v,y:a+c/2,textAnchor:m,verticalAnchor:"middle"},O):"insideTop"===o?g({x:i+u/2,y:a+f,textAnchor:"middle",verticalAnchor:d},O):"insideBottom"===o?g({x:i+u/2,y:a+c-f,textAnchor:"middle",verticalAnchor:p},O):"insideTopLeft"===o?g({x:i+v,y:a+f,textAnchor:b,verticalAnchor:d},O):"insideTopRight"===o?g({x:i+u-v,y:a+f,textAnchor:m,verticalAnchor:d},O):"insideBottomLeft"===o?g({x:i+v,y:a+c-f,textAnchor:b,verticalAnchor:p},O):"insideBottomRight"===o?g({x:i+u-v,y:a+c-f,textAnchor:m,verticalAnchor:p},O):l()(o)&&((0,h.hj)(o.x)||(0,h.hU)(o.x))&&((0,h.hj)(o.y)||(0,h.hU)(o.y))?g({x:i+(0,h.h1)(o.x,u),y:a+(0,h.h1)(o.y,c),textAnchor:"end",verticalAnchor:"end"},O):g({x:i+u/2,y:a+c/2,textAnchor:"middle",verticalAnchor:"middle"},O)};function P(t){var e,r=t.offset,o=g({offset:void 0===r?5:r},function(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,v)),a=o.viewBox,c=o.position,l=o.value,d=o.children,y=o.content,m=o.className,b=o.textBreakAll;if(!a||i()(l)&&i()(d)&&!(0,n.isValidElement)(y)&&!u()(y))return null;if((0,n.isValidElement)(y))return(0,n.cloneElement)(y,o);if(u()(y)){if(e=(0,n.createElement)(y,o),(0,n.isValidElement)(e))return e}else e=w(o);var P="cx"in a&&(0,h.hj)(a.cx),E=(0,p.L6)(o,!0);if(P&&("insideStart"===c||"insideEnd"===c||"end"===c))return O(o,e,E);var k=P?j(o):S(o);return n.createElement(f.x,x({className:(0,s.Z)("recharts-label",void 0===m?"":m)},E,k,{breakAll:b}),e)}P.displayName="Label";var E=function(t){var e=t.cx,r=t.cy,n=t.angle,o=t.startAngle,i=t.endAngle,a=t.r,u=t.radius,c=t.innerRadius,l=t.outerRadius,s=t.x,f=t.y,p=t.top,d=t.left,y=t.width,v=t.height,m=t.clockWise,b=t.labelViewBox;if(b)return b;if((0,h.hj)(y)&&(0,h.hj)(v)){if((0,h.hj)(s)&&(0,h.hj)(f))return{x:s,y:f,width:y,height:v};if((0,h.hj)(p)&&(0,h.hj)(d))return{x:p,y:d,width:y,height:v}}return(0,h.hj)(s)&&(0,h.hj)(f)?{x:s,y:f,width:0,height:0}:(0,h.hj)(e)&&(0,h.hj)(r)?{cx:e,cy:r,startAngle:o||n||0,endAngle:i||n||0,innerRadius:c||0,outerRadius:l||u||a||0,clockWise:m}:t.viewBox?t.viewBox:{}};P.parseViewBox=E,P.renderCallByParent=function(t,e){var r,o,i=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(!t||!t.children&&i&&!t.label)return null;var a=t.children,c=E(t),s=(0,p.NN)(a,P).map(function(t,r){return(0,n.cloneElement)(t,{viewBox:e||c,key:"label-".concat(r)})});return i?[(r=t.label,o=e||c,r?!0===r?n.createElement(P,{key:"label-implicit",viewBox:o}):(0,h.P2)(r)?n.createElement(P,{key:"label-implicit",viewBox:o,value:r}):(0,n.isValidElement)(r)?r.type===P?(0,n.cloneElement)(r,{key:"label-implicit",viewBox:o}):n.createElement(P,{key:"label-implicit",content:r,viewBox:o}):u()(r)?n.createElement(P,{key:"label-implicit",content:r,viewBox:o}):l()(r)?n.createElement(P,x({viewBox:o},r,{key:"label-implicit"})):null:null)].concat(function(t){if(Array.isArray(t))return m(t)}(s)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(s)||function(t,e){if(t){if("string"==typeof t)return m(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return m(t,void 0)}}(s)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()):s}},58772:function(t,e,r){"use strict";r.d(e,{e:function(){return P}});var n=r(2265),o=r(77571),i=r.n(o),a=r(28302),u=r.n(a),c=r(86757),l=r.n(c),s=r(86185),f=r.n(s),p=r(26680),h=r(9841),d=r(82944),y=r(85355);function v(t){return(v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var m=["valueAccessor"],b=["data","dataKey","clockWise","id","textBreakAll"];function g(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}var S=function(t){return Array.isArray(t.value)?f()(t.value):t.value};function P(t){var e=t.valueAccessor,r=void 0===e?S:e,o=j(t,m),a=o.data,u=o.dataKey,c=o.clockWise,l=o.id,s=o.textBreakAll,f=j(o,b);return a&&a.length?n.createElement(h.m,{className:"recharts-label-list"},a.map(function(t,e){var o=i()(u)?r(t,e):(0,y.F$)(t&&t.payload,u),a=i()(l)?{}:{id:"".concat(l,"-").concat(e)};return n.createElement(p._,x({},(0,d.L6)(t,!0),f,a,{parentViewBox:t.parentViewBox,value:o,textBreakAll:s,viewBox:p._.parseViewBox(i()(c)?t:O(O({},t),{},{clockWise:c})),key:"label-".concat(e),index:e}))})):null}P.displayName="LabelList",P.renderCallByParent=function(t,e){var r,o=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(!t||!t.children&&o&&!t.label)return null;var i=t.children,a=(0,d.NN)(i,P).map(function(t,r){return(0,n.cloneElement)(t,{data:e,key:"labelList-".concat(r)})});return o?[(r=t.label)?!0===r?n.createElement(P,{key:"labelList-implicit",data:e}):n.isValidElement(r)||l()(r)?n.createElement(P,{key:"labelList-implicit",data:e,content:r}):u()(r)?n.createElement(P,x({data:e},r,{key:"labelList-implicit"})):null:null].concat(function(t){if(Array.isArray(t))return g(t)}(a)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(a)||function(t,e){if(t){if("string"==typeof t)return g(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return g(t,void 0)}}(a)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()):a}},22190:function(t,e,r){"use strict";r.d(e,{D:function(){return N}});var n=r(2265),o=r(86757),i=r.n(o),a=r(61994),u=r(1175),c=r(48777),l=r(14870),s=r(41637);function f(t){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function p(){return(p=Object.assign?Object.assign.bind():function(t){for(var e=1;e');var x=e.inactive?h:e.color;return n.createElement("li",p({className:b,style:y,key:"legend-item-".concat(r)},(0,s.bw)(t.props,e,r)),n.createElement(c.T,{width:o,height:o,viewBox:d,style:v},t.renderIcon(e)),n.createElement("span",{className:"recharts-legend-item-text",style:{color:x}},l?l(g,e,r):g))})}},{key:"render",value:function(){var t=this.props,e=t.payload,r=t.layout,o=t.align;return e&&e.length?n.createElement("ul",{className:"recharts-default-legend",style:{padding:0,margin:0,textAlign:"horizontal"===r?o:"left"}},this.renderItems()):null}}],function(t,e){for(var r=0;r1||Math.abs(e.height-this.lastBoundingBox.height)>1)&&(this.lastBoundingBox.width=e.width,this.lastBoundingBox.height=e.height,t&&t(e)):(-1!==this.lastBoundingBox.width||-1!==this.lastBoundingBox.height)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,t&&t(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?P({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(t){var e,r,n=this.props,o=n.layout,i=n.align,a=n.verticalAlign,u=n.margin,c=n.chartWidth,l=n.chartHeight;return t&&(void 0!==t.left&&null!==t.left||void 0!==t.right&&null!==t.right)||(e="center"===i&&"vertical"===o?{left:((c||0)-this.getBBoxSnapshot().width)/2}:"right"===i?{right:u&&u.right||0}:{left:u&&u.left||0}),t&&(void 0!==t.top&&null!==t.top||void 0!==t.bottom&&null!==t.bottom)||(r="middle"===a?{top:((l||0)-this.getBBoxSnapshot().height)/2}:"bottom"===a?{bottom:u&&u.bottom||0}:{top:u&&u.top||0}),P(P({},e),r)}},{key:"render",value:function(){var t=this,e=this.props,r=e.content,o=e.width,i=e.height,a=e.wrapperStyle,u=e.payloadUniqBy,c=e.payload,l=P(P({position:"absolute",width:o||"auto",height:i||"auto"},this.getDefaultPosition(a)),a);return n.createElement("div",{className:"recharts-legend-wrapper",style:l,ref:function(e){t.wrapperNode=e}},function(t,e){if(n.isValidElement(t))return n.cloneElement(t,e);if("function"==typeof t)return n.createElement(t,e);e.ref;var r=function(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(e,j);return n.createElement(g,r)}(r,P(P({},this.props),{},{payload:(0,w.z)(c,u,C)})))}}],r=[{key:"getWithHeight",value:function(t,e){var r=P(P({},this.defaultProps),t.props).layout;return"vertical"===r&&(0,x.hj)(t.props.height)?{height:t.props.height}:"horizontal"===r?{width:t.props.width||e}:null}}],e&&E(o.prototype,e),r&&E(o,r),Object.defineProperty(o,"prototype",{writable:!1}),o}(n.PureComponent);_(N,"displayName","Legend"),_(N,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"})},47625:function(t,e,r){"use strict";r.d(e,{h:function(){return d}});var n=r(61994),o=r(2265),i=r(37065),a=r.n(i),u=r(16630),c=r(1175),l=r(82944);function s(t){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function f(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function p(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);r0&&(t=a()(t,S,{trailing:!0,leading:!1}));var e=new ResizeObserver(t),r=M.current.getBoundingClientRect();return D(r.width,r.height),e.observe(M.current),function(){e.disconnect()}},[D,S]);var I=(0,o.useMemo)(function(){var t=C.containerWidth,e=C.containerHeight;if(t<0||e<0)return null;(0,c.Z)((0,u.hU)(y)||(0,u.hU)(m),"The width(%s) and height(%s) are both fixed numbers,\n maybe you don't need to use a ResponsiveContainer.",y,m),(0,c.Z)(!i||i>0,"The aspect(%s) must be greater than zero.",i);var r=(0,u.hU)(y)?t:y,n=(0,u.hU)(m)?e:m;i&&i>0&&(r?n=r/i:n&&(r=n*i),w&&n>w&&(n=w)),(0,c.Z)(r>0||n>0,"The width(%s) and height(%s) of chart should be greater than 0,\n please check the style of container, or the props width(%s) and height(%s),\n or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the\n height and width.",r,n,y,m,g,x,i);var a=!Array.isArray(O)&&(0,l.Gf)(O.type).endsWith("Chart");return o.Children.map(O,function(t){return o.isValidElement(t)?(0,o.cloneElement)(t,p({width:r,height:n},a?{style:p({height:"100%",width:"100%",maxHeight:n,maxWidth:r},t.props.style)}:{})):t})},[i,O,m,w,x,g,C,y]);return o.createElement("div",{id:P?"".concat(P):void 0,className:(0,n.Z)("recharts-responsive-container",E),style:p(p({},void 0===A?{}:A),{},{width:y,height:m,minWidth:g,minHeight:x,maxHeight:w}),ref:M},I)})},58811:function(t,e,r){"use strict";r.d(e,{x:function(){return B}});var n=r(2265),o=r(77571),i=r.n(o),a=r(61994),u=r(16630),c=r(34067),l=r(82944),s=r(4094);function f(t){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function p(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(u.push(n.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return h(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return h(t,e)}}(t,e)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function M(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(u.push(n.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return _(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return _(t,e)}}(t,e)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r0&&void 0!==arguments[0]?arguments[0]:[];return t.reduce(function(t,e){var i=e.word,a=e.width,u=t[t.length-1];return u&&(null==n||o||u.width+a+ra||e.reduce(function(t,e){return t.width>e.width?t:e}).width>Number(n),e]},y=0,v=c.length-1,m=0;y<=v&&m<=c.length-1;){var b=Math.floor((y+v)/2),g=M(d(b-1),2),x=g[0],w=g[1],O=M(d(b),1)[0];if(x||O||(y=b+1),x&&O&&(v=b-1),!x&&O){i=w;break}m++}return i||h},D=function(t){return[{words:i()(t)?[]:t.toString().split(T)}]},I=function(t){var e=t.width,r=t.scaleToFit,n=t.children,o=t.style,i=t.breakAll,a=t.maxLines;if((e||r)&&!c.x.isSsr){var u=C({breakAll:i,children:n,style:o});return u?N({breakAll:i,children:n,maxLines:a,style:o},u.wordsWithComputedWidth,u.spaceWidth,e,r):D(n)}return D(n)},L="#808080",B=function(t){var e,r=t.x,o=void 0===r?0:r,i=t.y,c=void 0===i?0:i,s=t.lineHeight,f=void 0===s?"1em":s,p=t.capHeight,h=void 0===p?"0.71em":p,d=t.scaleToFit,y=void 0!==d&&d,v=t.textAnchor,m=t.verticalAnchor,b=t.fill,g=void 0===b?L:b,x=A(t,P),w=(0,n.useMemo)(function(){return I({breakAll:x.breakAll,children:x.children,maxLines:x.maxLines,scaleToFit:y,style:x.style,width:x.width})},[x.breakAll,x.children,x.maxLines,y,x.style,x.width]),O=x.dx,j=x.dy,M=x.angle,_=x.className,T=x.breakAll,C=A(x,E);if(!(0,u.P2)(o)||!(0,u.P2)(c))return null;var N=o+((0,u.hj)(O)?O:0),D=c+((0,u.hj)(j)?j:0);switch(void 0===m?"end":m){case"start":e=S("calc(".concat(h,")"));break;case"middle":e=S("calc(".concat((w.length-1)/2," * -").concat(f," + (").concat(h," / 2))"));break;default:e=S("calc(".concat(w.length-1," * -").concat(f,")"))}var B=[];if(y){var R=w[0].width,z=x.width;B.push("scale(".concat(((0,u.hj)(z)?z/R:1)/R,")"))}return M&&B.push("rotate(".concat(M,", ").concat(N,", ").concat(D,")")),B.length&&(C.transform=B.join(" ")),n.createElement("text",k({},(0,l.L6)(C,!0),{x:N,y:D,className:(0,a.Z)("recharts-text",_),textAnchor:void 0===v?"start":v,fill:g.includes("url")?L:g}),w.map(function(t,r){var o=t.words.join(T?"":" ");return n.createElement("tspan",{x:N,dy:0===r?e:f,key:"".concat(o,"-").concat(r)},o)}))}},8147:function(t,e,r){"use strict";r.d(e,{u:function(){return $}});var n=r(2265),o=r(34935),i=r.n(o),a=r(77571),u=r.n(a),c=r(61994),l=r(16630);function s(t){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function f(){return(f=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);rc[n]+s?Math.max(f,c[n]):Math.max(p,c[n])}function O(t){return(O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function j(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function S(t){for(var e=1;e1||Math.abs(t.height-this.state.lastBoundingBox.height)>1)&&this.setState({lastBoundingBox:{width:t.width,height:t.height}})}else(-1!==this.state.lastBoundingBox.width||-1!==this.state.lastBoundingBox.height)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var t,e;this.props.active&&this.updateBBox(),this.state.dismissed&&((null===(t=this.props.coordinate)||void 0===t?void 0:t.x)!==this.state.dismissedAtCoordinate.x||(null===(e=this.props.coordinate)||void 0===e?void 0:e.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var t,e,r,o,i,a,u,s,f,p,h,d,y,v,m,O,j,P,E,k=this,A=this.props,M=A.active,_=A.allowEscapeViewBox,T=A.animationDuration,C=A.animationEasing,N=A.children,D=A.coordinate,I=A.hasPayload,L=A.isAnimationActive,B=A.offset,R=A.position,z=A.reverseDirection,U=A.useTranslate3d,F=A.viewBox,$=A.wrapperStyle,q=(d=(t={allowEscapeViewBox:_,coordinate:D,offsetTopLeft:B,position:R,reverseDirection:z,tooltipBox:this.state.lastBoundingBox,useTranslate3d:U,viewBox:F}).allowEscapeViewBox,y=t.coordinate,v=t.offsetTopLeft,m=t.position,O=t.reverseDirection,j=t.tooltipBox,P=t.useTranslate3d,E=t.viewBox,j.height>0&&j.width>0&&y?(r=(e={translateX:p=w({allowEscapeViewBox:d,coordinate:y,key:"x",offsetTopLeft:v,position:m,reverseDirection:O,tooltipDimension:j.width,viewBox:E,viewBoxDimension:E.width}),translateY:h=w({allowEscapeViewBox:d,coordinate:y,key:"y",offsetTopLeft:v,position:m,reverseDirection:O,tooltipDimension:j.height,viewBox:E,viewBoxDimension:E.height}),useTranslate3d:P}).translateX,o=e.translateY,f={transform:e.useTranslate3d?"translate3d(".concat(r,"px, ").concat(o,"px, 0)"):"translate(".concat(r,"px, ").concat(o,"px)")}):f=x,{cssProperties:f,cssClasses:(a=(i={translateX:p,translateY:h,coordinate:y}).coordinate,u=i.translateX,s=i.translateY,(0,c.Z)(g,b(b(b(b({},"".concat(g,"-right"),(0,l.hj)(u)&&a&&(0,l.hj)(a.x)&&u>=a.x),"".concat(g,"-left"),(0,l.hj)(u)&&a&&(0,l.hj)(a.x)&&u=a.y),"".concat(g,"-top"),(0,l.hj)(s)&&a&&(0,l.hj)(a.y)&&s0;return n.createElement(_,{allowEscapeViewBox:i,animationDuration:a,animationEasing:u,isAnimationActive:f,active:o,coordinate:l,hasPayload:O,offset:p,position:y,reverseDirection:m,useTranslate3d:b,viewBox:g,wrapperStyle:x},(t=I(I({},this.props),{},{payload:w}),n.isValidElement(c)?n.cloneElement(c,t):"function"==typeof c?n.createElement(c,t):n.createElement(v,t)))}}],function(t,e){for(var r=0;r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,a),s=(0,o.Z)("recharts-layer",c);return n.createElement("g",u({className:s},(0,i.L6)(l,!0),{ref:e}),r)})},48777:function(t,e,r){"use strict";r.d(e,{T:function(){return c}});var n=r(2265),o=r(61994),i=r(82944),a=["children","width","height","viewBox","className","style","title","desc"];function u(){return(u=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,a),y=l||{width:r,height:c,x:0,y:0},v=(0,o.Z)("recharts-surface",s);return n.createElement("svg",u({},(0,i.L6)(d,!0,"svg"),{className:v,width:r,height:c,style:f,viewBox:"".concat(y.x," ").concat(y.y," ").concat(y.width," ").concat(y.height)}),n.createElement("title",null,p),n.createElement("desc",null,h),e)}},25739:function(t,e,r){"use strict";r.d(e,{br:function(){return g},CW:function(){return O},Mw:function(){return A},zn:function(){return k},sp:function(){return x},qD:function(){return E},d2:function(){return P},bH:function(){return w},Ud:function(){return S},Nf:function(){return j}});var n=r(2265),o=r(69398),i=r(84173),a=r.n(i),u=r(32242),c=r.n(u),l=r(50967),s=r.n(l)()(function(t){return{x:t.left,y:t.top,width:t.width,height:t.height}},function(t){return["l",t.left,"t",t.top,"w",t.width,"h",t.height].join("")}),f=r(16630),p=(0,n.createContext)(void 0),h=(0,n.createContext)(void 0),d=(0,n.createContext)(void 0),y=(0,n.createContext)({}),v=(0,n.createContext)(void 0),m=(0,n.createContext)(0),b=(0,n.createContext)(0),g=function(t){var e=t.state,r=e.xAxisMap,o=e.yAxisMap,i=e.offset,a=t.clipPathId,u=t.children,c=t.width,l=t.height,f=s(i);return n.createElement(p.Provider,{value:r},n.createElement(h.Provider,{value:o},n.createElement(y.Provider,{value:i},n.createElement(d.Provider,{value:f},n.createElement(v.Provider,{value:a},n.createElement(m.Provider,{value:l},n.createElement(b.Provider,{value:c},u)))))))},x=function(){return(0,n.useContext)(v)},w=function(t){var e=(0,n.useContext)(p);null!=e||(0,o.Z)(!1);var r=e[t];return null!=r||(0,o.Z)(!1),r},O=function(){var t=(0,n.useContext)(p);return(0,f.Kt)(t)},j=function(){var t=(0,n.useContext)(h);return a()(t,function(t){return c()(t.domain,Number.isFinite)})||(0,f.Kt)(t)},S=function(t){var e=(0,n.useContext)(h);null!=e||(0,o.Z)(!1);var r=e[t];return null!=r||(0,o.Z)(!1),r},P=function(){return(0,n.useContext)(d)},E=function(){return(0,n.useContext)(y)},k=function(){return(0,n.useContext)(b)},A=function(){return(0,n.useContext)(m)}},57165:function(t,e,r){"use strict";r.d(e,{H:function(){return H}});var n=r(2265);function o(){}function i(t,e,r){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+r)/6)}function a(t){this._context=t}function u(t){this._context=t}function c(t){this._context=t}a.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:i(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:i(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},u.prototype={areaStart:o,areaEnd:o,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:i(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},c.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+t)/6,n=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:i(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};class l{constructor(t,e){this._context=t,this._x=e}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,e,t,e):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+e)/2,t,this._y0,t,e)}this._x0=t,this._y0=e}}function s(t){this._context=t}function f(t){this._context=t}function p(t){return new f(t)}function h(t,e,r){var n=t._x1-t._x0,o=e-t._x1,i=(t._y1-t._y0)/(n||o<0&&-0),a=(r-t._y1)/(o||n<0&&-0);return((i<0?-1:1)+(a<0?-1:1))*Math.min(Math.abs(i),Math.abs(a),.5*Math.abs((i*o+a*n)/(n+o)))||0}function d(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function y(t,e,r){var n=t._x0,o=t._y0,i=t._x1,a=t._y1,u=(i-n)/3;t._context.bezierCurveTo(n+u,o+u*e,i-u,a-u*r,i,a)}function v(t){this._context=t}function m(t){this._context=new b(t)}function b(t){this._context=t}function g(t){this._context=t}function x(t){var e,r,n=t.length-1,o=Array(n),i=Array(n),a=Array(n);for(o[0]=0,i[0]=2,a[0]=t[0]+2*t[1],e=1;e=0;--e)o[e]=(a[e]-o[e+1])/i[e];for(e=0,i[n-1]=(t[n]+o[n-1])/2;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var r=this._x*(1-this._t)+t*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,e)}}this._x=t,this._y=e}};var O=r(22516),j=r(76115),S=r(67790);function P(t){return t[0]}function E(t){return t[1]}function k(t,e){var r=(0,j.Z)(!0),n=null,o=p,i=null,a=(0,S.d)(u);function u(u){var c,l,s,f=(u=(0,O.Z)(u)).length,p=!1;for(null==n&&(i=o(s=a())),c=0;c<=f;++c)!(c=f;--p)u.point(m[p],b[p]);u.lineEnd(),u.areaEnd()}}v&&(m[s]=+t(h,s,l),b[s]=+e(h,s,l),u.point(n?+n(h,s,l):m[s],r?+r(h,s,l):b[s]))}if(d)return u=null,d+""||null}function s(){return k().defined(o).curve(a).context(i)}return t="function"==typeof t?t:void 0===t?P:(0,j.Z)(+t),e="function"==typeof e?e:void 0===e?(0,j.Z)(0):(0,j.Z)(+e),r="function"==typeof r?r:void 0===r?E:(0,j.Z)(+r),l.x=function(e){return arguments.length?(t="function"==typeof e?e:(0,j.Z)(+e),n=null,l):t},l.x0=function(e){return arguments.length?(t="function"==typeof e?e:(0,j.Z)(+e),l):t},l.x1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:(0,j.Z)(+t),l):n},l.y=function(t){return arguments.length?(e="function"==typeof t?t:(0,j.Z)(+t),r=null,l):e},l.y0=function(t){return arguments.length?(e="function"==typeof t?t:(0,j.Z)(+t),l):e},l.y1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:(0,j.Z)(+t),l):r},l.lineX0=l.lineY0=function(){return s().x(t).y(e)},l.lineY1=function(){return s().x(t).y(r)},l.lineX1=function(){return s().x(n).y(e)},l.defined=function(t){return arguments.length?(o="function"==typeof t?t:(0,j.Z)(!!t),l):o},l.curve=function(t){return arguments.length?(a=t,null!=i&&(u=a(i)),l):a},l.context=function(t){return arguments.length?(null==t?i=u=null:u=a(i=t),l):i},l}var M=r(75551),_=r.n(M),T=r(86757),C=r.n(T),N=r(61994),D=r(41637),I=r(82944),L=r(16630);function B(t){return(B="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function R(){return(R=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);r=0?1:-1,c=r>=0?1:-1,l=n>=0&&r>=0||n<0&&r<0?1:0;if(a>0&&o instanceof Array){for(var s=[0,0,0,0],f=0;f<4;f++)s[f]=o[f]>a?a:o[f];i="M".concat(t,",").concat(e+u*s[0]),s[0]>0&&(i+="A ".concat(s[0],",").concat(s[0],",0,0,").concat(l,",").concat(t+c*s[0],",").concat(e)),i+="L ".concat(t+r-c*s[1],",").concat(e),s[1]>0&&(i+="A ".concat(s[1],",").concat(s[1],",0,0,").concat(l,",\n ").concat(t+r,",").concat(e+u*s[1])),i+="L ".concat(t+r,",").concat(e+n-u*s[2]),s[2]>0&&(i+="A ".concat(s[2],",").concat(s[2],",0,0,").concat(l,",\n ").concat(t+r-c*s[2],",").concat(e+n)),i+="L ".concat(t+c*s[3],",").concat(e+n),s[3]>0&&(i+="A ".concat(s[3],",").concat(s[3],",0,0,").concat(l,",\n ").concat(t,",").concat(e+n-u*s[3])),i+="Z"}else if(a>0&&o===+o&&o>0){var p=Math.min(a,o);i="M ".concat(t,",").concat(e+u*p,"\n A ").concat(p,",").concat(p,",0,0,").concat(l,",").concat(t+c*p,",").concat(e,"\n L ").concat(t+r-c*p,",").concat(e,"\n A ").concat(p,",").concat(p,",0,0,").concat(l,",").concat(t+r,",").concat(e+u*p,"\n L ").concat(t+r,",").concat(e+n-u*p,"\n A ").concat(p,",").concat(p,",0,0,").concat(l,",").concat(t+r-c*p,",").concat(e+n,"\n L ").concat(t+c*p,",").concat(e+n,"\n A ").concat(p,",").concat(p,",0,0,").concat(l,",").concat(t,",").concat(e+n-u*p," Z")}else i="M ".concat(t,",").concat(e," h ").concat(r," v ").concat(n," h ").concat(-r," Z");return i},h=function(t,e){if(!t||!e)return!1;var r=t.x,n=t.y,o=e.x,i=e.y,a=e.width,u=e.height;return!!(Math.abs(a)>0&&Math.abs(u)>0)&&r>=Math.min(o,o+a)&&r<=Math.max(o,o+a)&&n>=Math.min(i,i+u)&&n<=Math.max(i,i+u)},d={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},y=function(t){var e,r=f(f({},d),t),u=(0,n.useRef)(),s=function(t){if(Array.isArray(t))return t}(e=(0,n.useState)(-1))||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{for(i=(r=r.call(t)).next;!(c=(n=i.call(r)).done)&&(u.push(n.value),2!==u.length);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(e,2)||function(t,e){if(t){if("string"==typeof t)return l(t,2);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return l(t,2)}}(e,2)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(),h=s[0],y=s[1];(0,n.useEffect)(function(){if(u.current&&u.current.getTotalLength)try{var t=u.current.getTotalLength();t&&y(t)}catch(t){}},[]);var v=r.x,m=r.y,b=r.width,g=r.height,x=r.radius,w=r.className,O=r.animationEasing,j=r.animationDuration,S=r.animationBegin,P=r.isAnimationActive,E=r.isUpdateAnimationActive;if(v!==+v||m!==+m||b!==+b||g!==+g||0===b||0===g)return null;var k=(0,o.Z)("recharts-rectangle",w);return E?n.createElement(i.ZP,{canBegin:h>0,from:{width:b,height:g,x:v,y:m},to:{width:b,height:g,x:v,y:m},duration:j,animationEasing:O,isActive:E},function(t){var e=t.width,o=t.height,l=t.x,s=t.y;return n.createElement(i.ZP,{canBegin:h>0,from:"0px ".concat(-1===h?1:h,"px"),to:"".concat(h,"px 0px"),attributeName:"strokeDasharray",begin:S,duration:j,isActive:P,easing:O},n.createElement("path",c({},(0,a.L6)(r,!0),{className:k,d:p(l,s,e,o,x),ref:u})))}):n.createElement("path",c({},(0,a.L6)(r,!0),{className:k,d:p(v,m,b,g,x)}))}},60474:function(t,e,r){"use strict";r.d(e,{L:function(){return v}});var n=r(2265),o=r(61994),i=r(82944),a=r(39206),u=r(16630);function c(t){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function l(){return(l=Object.assign?Object.assign.bind():function(t){for(var e=1;e180),",").concat(+(c>s),",\n ").concat(p.x,",").concat(p.y,"\n ");if(o>0){var d=(0,a.op)(r,n,o,c),y=(0,a.op)(r,n,o,s);h+="L ".concat(y.x,",").concat(y.y,"\n A ").concat(o,",").concat(o,",0,\n ").concat(+(Math.abs(l)>180),",").concat(+(c<=s),",\n ").concat(d.x,",").concat(d.y," Z")}else h+="L ".concat(r,",").concat(n," Z");return h},d=function(t){var e=t.cx,r=t.cy,n=t.innerRadius,o=t.outerRadius,i=t.cornerRadius,a=t.forceCornerRadius,c=t.cornerIsExternal,l=t.startAngle,s=t.endAngle,f=(0,u.uY)(s-l),d=p({cx:e,cy:r,radius:o,angle:l,sign:f,cornerRadius:i,cornerIsExternal:c}),y=d.circleTangency,v=d.lineTangency,m=d.theta,b=p({cx:e,cy:r,radius:o,angle:s,sign:-f,cornerRadius:i,cornerIsExternal:c}),g=b.circleTangency,x=b.lineTangency,w=b.theta,O=c?Math.abs(l-s):Math.abs(l-s)-m-w;if(O<0)return a?"M ".concat(v.x,",").concat(v.y,"\n a").concat(i,",").concat(i,",0,0,1,").concat(2*i,",0\n a").concat(i,",").concat(i,",0,0,1,").concat(-(2*i),",0\n "):h({cx:e,cy:r,innerRadius:n,outerRadius:o,startAngle:l,endAngle:s});var j="M ".concat(v.x,",").concat(v.y,"\n A").concat(i,",").concat(i,",0,0,").concat(+(f<0),",").concat(y.x,",").concat(y.y,"\n A").concat(o,",").concat(o,",0,").concat(+(O>180),",").concat(+(f<0),",").concat(g.x,",").concat(g.y,"\n A").concat(i,",").concat(i,",0,0,").concat(+(f<0),",").concat(x.x,",").concat(x.y,"\n ");if(n>0){var S=p({cx:e,cy:r,radius:n,angle:l,sign:f,isExternal:!0,cornerRadius:i,cornerIsExternal:c}),P=S.circleTangency,E=S.lineTangency,k=S.theta,A=p({cx:e,cy:r,radius:n,angle:s,sign:-f,isExternal:!0,cornerRadius:i,cornerIsExternal:c}),M=A.circleTangency,_=A.lineTangency,T=A.theta,C=c?Math.abs(l-s):Math.abs(l-s)-k-T;if(C<0&&0===i)return"".concat(j,"L").concat(e,",").concat(r,"Z");j+="L".concat(_.x,",").concat(_.y,"\n A").concat(i,",").concat(i,",0,0,").concat(+(f<0),",").concat(M.x,",").concat(M.y,"\n A").concat(n,",").concat(n,",0,").concat(+(C>180),",").concat(+(f>0),",").concat(P.x,",").concat(P.y,"\n A").concat(i,",").concat(i,",0,0,").concat(+(f<0),",").concat(E.x,",").concat(E.y,"Z")}else j+="L".concat(e,",").concat(r,"Z");return j},y={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},v=function(t){var e,r=f(f({},y),t),a=r.cx,c=r.cy,s=r.innerRadius,p=r.outerRadius,v=r.cornerRadius,m=r.forceCornerRadius,b=r.cornerIsExternal,g=r.startAngle,x=r.endAngle,w=r.className;if(p0&&360>Math.abs(g-x)?d({cx:a,cy:c,innerRadius:s,outerRadius:p,cornerRadius:Math.min(S,j/2),forceCornerRadius:m,cornerIsExternal:b,startAngle:g,endAngle:x}):h({cx:a,cy:c,innerRadius:s,outerRadius:p,startAngle:g,endAngle:x}),n.createElement("path",l({},(0,i.L6)(r,!0),{className:O,d:e,role:"img"}))}},14870:function(t,e,r){"use strict";r.d(e,{v:function(){return N}});var n=r(2265),o=r(75551),i=r.n(o);let a=Math.cos,u=Math.sin,c=Math.sqrt,l=Math.PI,s=2*l;var f={draw(t,e){let r=c(e/l);t.moveTo(r,0),t.arc(0,0,r,0,s)}};let p=c(1/3),h=2*p,d=u(l/10)/u(7*l/10),y=u(s/10)*d,v=-a(s/10)*d,m=c(3),b=c(3)/2,g=1/c(12),x=(g/2+1)*3;var w=r(76115),O=r(67790);c(3),c(3);var j=r(61994),S=r(82944);function P(t){return(P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var E=["type","size","sizeType"];function k(){return(k=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,E)),{},{type:o,size:u,sizeType:l}),p=s.className,h=s.cx,d=s.cy,y=(0,S.L6)(s,!0);return h===+h&&d===+d&&u===+u?n.createElement("path",k({},y,{className:(0,j.Z)("recharts-symbols",p),transform:"translate(".concat(h,", ").concat(d,")"),d:(e=_["symbol".concat(i()(o))]||f,(function(t,e){let r=null,n=(0,O.d)(o);function o(){let o;if(r||(r=o=n()),t.apply(this,arguments).draw(r,+e.apply(this,arguments)),o)return r=null,o+""||null}return t="function"==typeof t?t:(0,w.Z)(t||f),e="function"==typeof e?e:(0,w.Z)(void 0===e?64:+e),o.type=function(e){return arguments.length?(t="function"==typeof e?e:(0,w.Z)(e),o):t},o.size=function(t){return arguments.length?(e="function"==typeof t?t:(0,w.Z)(+t),o):e},o.context=function(t){return arguments.length?(r=null==t?null:t,o):r},o})().type(e).size(C(u,l,o))())})):null};N.registerSymbol=function(t,e){_["symbol".concat(i()(t))]=e}},11638:function(t,e,r){"use strict";r.d(e,{bn:function(){return C},a3:function(){return z},lT:function(){return N},V$:function(){return D},w7:function(){return I}});var n=r(2265),o=r(86757),i=r.n(o),a=r(90231),u=r.n(a),c=r(24342),l=r.n(c),s=r(21652),f=r.n(s),p=r(73649),h=r(61994),d=r(84735),y=r(82944);function v(t){return(v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function m(){return(m=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);r0,from:{upperWidth:0,lowerWidth:0,height:p,x:c,y:l},to:{upperWidth:s,lowerWidth:f,height:p,x:c,y:l},duration:j,animationEasing:g,isActive:P},function(t){var e=t.upperWidth,i=t.lowerWidth,u=t.height,c=t.x,l=t.y;return n.createElement(d.ZP,{canBegin:a>0,from:"0px ".concat(-1===a?1:a,"px"),to:"".concat(a,"px 0px"),attributeName:"strokeDasharray",begin:S,duration:j,easing:g},n.createElement("path",m({},(0,y.L6)(r,!0),{className:E,d:w(c,l,e,i,u),ref:o})))}):n.createElement("g",null,n.createElement("path",m({},(0,y.L6)(r,!0),{className:E,d:w(c,l,s,f,p)})))},S=r(60474),P=r(9841),E=r(14870),k=["option","shapeType","propTransformer","activeClassName","isActive"];function A(t){return(A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function M(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function _(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,k);if((0,n.isValidElement)(r))e=(0,n.cloneElement)(r,_(_({},f),(0,n.isValidElement)(r)?r.props:r));else if(i()(r))e=r(f);else if(u()(r)&&!l()(r)){var p=(void 0===a?function(t,e){return _(_({},e),t)}:a)(r,f);e=n.createElement(T,{shapeType:o,elementProps:p})}else e=n.createElement(T,{shapeType:o,elementProps:f});return s?n.createElement(P.m,{className:void 0===c?"recharts-active-shape":c},e):e}function N(t,e){return null!=e&&"trapezoids"in t.props}function D(t,e){return null!=e&&"sectors"in t.props}function I(t,e){return null!=e&&"points"in t.props}function L(t,e){var r,n,o=t.x===(null==e||null===(r=e.labelViewBox)||void 0===r?void 0:r.x)||t.x===e.x,i=t.y===(null==e||null===(n=e.labelViewBox)||void 0===n?void 0:n.y)||t.y===e.y;return o&&i}function B(t,e){var r=t.endAngle===e.endAngle,n=t.startAngle===e.startAngle;return r&&n}function R(t,e){var r=t.x===e.x,n=t.y===e.y,o=t.z===e.z;return r&&n&&o}function z(t){var e,r,n,o=t.activeTooltipItem,i=t.graphicalItem,a=t.itemData,u=(N(i,o)?e="trapezoids":D(i,o)?e="sectors":I(i,o)&&(e="points"),e),c=N(i,o)?null===(r=o.tooltipPayload)||void 0===r||null===(r=r[0])||void 0===r||null===(r=r.payload)||void 0===r?void 0:r.payload:D(i,o)?null===(n=o.tooltipPayload)||void 0===n||null===(n=n[0])||void 0===n||null===(n=n.payload)||void 0===n?void 0:n.payload:I(i,o)?o.payload:{},l=a.filter(function(t,e){var r=f()(c,t),n=i.props[u].filter(function(t){var e;return(N(i,o)?e=L:D(i,o)?e=B:I(i,o)&&(e=R),e)(t,o)}),a=i.props[u].indexOf(n[n.length-1]);return r&&e===a});return a.indexOf(l[l.length-1])}},25311:function(t,e,r){"use strict";r.d(e,{Ky:function(){return w},O1:function(){return b},_b:function(){return g},t9:function(){return m},xE:function(){return O}});var n=r(41443),o=r.n(n),i=r(32242),a=r.n(i),u=r(85355),c=r(82944),l=r(16630),s=r(31699);function f(t){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function p(t,e){for(var r=0;r0&&(A=Math.min((t||0)-(M[e-1]||0),A))}),Number.isFinite(A)){var _=A/k,T="vertical"===g.layout?r.height:r.width;if("gap"===g.padding&&(c=_*T/2),"no-gap"===g.padding){var C=(0,l.h1)(t.barCategoryGap,_*T),N=_*T/2;c=N-C-(N-C)/T*C}}}s="xAxis"===n?[r.left+(j.left||0)+(c||0),r.left+r.width-(j.right||0)-(c||0)]:"yAxis"===n?"horizontal"===f?[r.top+r.height-(j.bottom||0),r.top+(j.top||0)]:[r.top+(j.top||0)+(c||0),r.top+r.height-(j.bottom||0)-(c||0)]:g.range,P&&(s=[s[1],s[0]]);var D=(0,u.Hq)(g,o,m),I=D.scale,L=D.realScaleType;I.domain(w).range(s),(0,u.zF)(I);var B=(0,u.g$)(I,d(d({},g),{},{realScaleType:L}));"xAxis"===n?(b="top"===x&&!S||"bottom"===x&&S,p=r.left,h=v[E]-b*g.height):"yAxis"===n&&(b="left"===x&&!S||"right"===x&&S,p=v[E]-b*g.width,h=r.top);var R=d(d(d({},g),B),{},{realScaleType:L,x:p,y:h,scale:I,width:"xAxis"===n?r.width:g.width,height:"yAxis"===n?r.height:g.height});return R.bandSize=(0,u.zT)(R,B),g.hide||"xAxis"!==n?g.hide||(v[E]+=(b?-1:1)*R.width):v[E]+=(b?-1:1)*R.height,d(d({},i),{},y({},a,R))},{})},b=function(t,e){var r=t.x,n=t.y,o=e.x,i=e.y;return{x:Math.min(r,o),y:Math.min(n,i),width:Math.abs(o-r),height:Math.abs(i-n)}},g=function(t){return b({x:t.x1,y:t.y1},{x:t.x2,y:t.y2})},x=function(){var t,e;function r(t){!function(t,e){if(!(t instanceof e))throw TypeError("Cannot call a class as a function")}(this,r),this.scale=t}return t=[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.bandAware,n=e.position;if(void 0!==t){if(n)switch(n){case"start":default:return this.scale(t);case"middle":var o=this.bandwidth?this.bandwidth()/2:0;return this.scale(t)+o;case"end":var i=this.bandwidth?this.bandwidth():0;return this.scale(t)+i}if(r){var a=this.bandwidth?this.bandwidth()/2:0;return this.scale(t)+a}return this.scale(t)}}},{key:"isInRange",value:function(t){var e=this.range(),r=e[0],n=e[e.length-1];return r<=n?t>=r&&t<=n:t>=n&&t<=r}}],e=[{key:"create",value:function(t){return new r(t)}}],t&&p(r.prototype,t),e&&p(r,e),Object.defineProperty(r,"prototype",{writable:!1}),r}();y(x,"EPS",1e-4);var w=function(t){var e=Object.keys(t).reduce(function(e,r){return d(d({},e),{},y({},r,x.create(t[r])))},{});return d(d({},e),{},{apply:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.bandAware,i=r.position;return o()(t,function(t,r){return e[r].apply(t,{bandAware:n,position:i})})},isInRange:function(t){return a()(t,function(t,r){return e[r].isInRange(t)})}})},O=function(t){var e=t.width,r=t.height,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=(n%180+180)%180*Math.PI/180,i=Math.atan(r/e);return Math.abs(o>i&&otx(e,t()).base(e.base()),tj.o.apply(e,arguments),e}},scaleOrdinal:function(){return tX.Z},scalePoint:function(){return f.x},scalePow:function(){return tJ},scaleQuantile:function(){return function t(){var e,r=[],n=[],o=[];function i(){var t=0,e=Math.max(1,n.length);for(o=Array(e-1);++t=1)return+r(t[n-1],n-1,t);var n,o=(n-1)*e,i=Math.floor(o),a=+r(t[i],i,t);return a+(+r(t[i+1],i+1,t)-a)*(o-i)}}(r,t/e);return a}function a(t){return null==t||isNaN(t=+t)?e:n[P(o,t)]}return a.invertExtent=function(t){var e=n.indexOf(t);return e<0?[NaN,NaN]:[e>0?o[e-1]:r[0],e=o?[i[o-1],n]:[i[e-1],i[e]]},u.unknown=function(t){return arguments.length&&(e=t),u},u.thresholds=function(){return i.slice()},u.copy=function(){return t().domain([r,n]).range(a).unknown(e)},tj.o.apply(tI(u),arguments)}},scaleRadial:function(){return function t(){var e,r=tO(),n=[0,1],o=!1;function i(t){var n,i=Math.sign(n=r(t))*Math.sqrt(Math.abs(n));return isNaN(i)?e:o?Math.round(i):i}return i.invert=function(t){return r.invert(t1(t))},i.domain=function(t){return arguments.length?(r.domain(t),i):r.domain()},i.range=function(t){return arguments.length?(r.range((n=Array.from(t,td)).map(t1)),i):n.slice()},i.rangeRound=function(t){return i.range(t).round(!0)},i.round=function(t){return arguments.length?(o=!!t,i):o},i.clamp=function(t){return arguments.length?(r.clamp(t),i):r.clamp()},i.unknown=function(t){return arguments.length?(e=t,i):e},i.copy=function(){return t(r.domain(),n).round(o).clamp(r.clamp()).unknown(e)},tj.o.apply(i,arguments),tI(i)}},scaleSequential:function(){return function t(){var e=tI(rX()(tv));return e.copy=function(){return rG(e,t())},tj.O.apply(e,arguments)}},scaleSequentialLog:function(){return function t(){var e=tZ(rX()).domain([1,10]);return e.copy=function(){return rG(e,t()).base(e.base())},tj.O.apply(e,arguments)}},scaleSequentialPow:function(){return rV},scaleSequentialQuantile:function(){return function t(){var e=[],r=tv;function n(t){if(null!=t&&!isNaN(t=+t))return r((P(e,t,1)-1)/(e.length-1))}return n.domain=function(t){if(!arguments.length)return e.slice();for(let r of(e=[],t))null==r||isNaN(r=+r)||e.push(r);return e.sort(g),n},n.interpolator=function(t){return arguments.length?(r=t,n):r},n.range=function(){return e.map((t,n)=>r(n/(e.length-1)))},n.quantiles=function(t){return Array.from({length:t+1},(r,n)=>(function(t,e,r){if(!(!(n=(t=Float64Array.from(function*(t,e){if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(yield e);else{let r=-1;for(let n of t)null!=(n=e(n,++r,t))&&(n=+n)>=n&&(yield n)}}(t,void 0))).length)||isNaN(e=+e))){if(e<=0||n<2)return t5(t);if(e>=1)return t2(t);var n,o=(n-1)*e,i=Math.floor(o),a=t2((function t(e,r,n=0,o=1/0,i){if(r=Math.floor(r),n=Math.floor(Math.max(0,n)),o=Math.floor(Math.min(e.length-1,o)),!(n<=r&&r<=o))return e;for(i=void 0===i?t6:function(t=g){if(t===g)return t6;if("function"!=typeof t)throw TypeError("compare is not a function");return(e,r)=>{let n=t(e,r);return n||0===n?n:(0===t(r,r))-(0===t(e,e))}}(i);o>n;){if(o-n>600){let a=o-n+1,u=r-n+1,c=Math.log(a),l=.5*Math.exp(2*c/3),s=.5*Math.sqrt(c*l*(a-l)/a)*(u-a/2<0?-1:1),f=Math.max(n,Math.floor(r-u*l/a+s)),p=Math.min(o,Math.floor(r+(a-u)*l/a+s));t(e,r,f,p,i)}let a=e[r],u=n,c=o;for(t3(e,n,r),i(e[o],a)>0&&t3(e,n,o);ui(e[u],a);)++u;for(;i(e[c],a)>0;)--c}0===i(e[n],a)?t3(e,n,c):t3(e,++c,o),c<=r&&(n=c+1),r<=c&&(o=c-1)}return e})(t,i).subarray(0,i+1));return a+(t5(t.subarray(i+1))-a)*(o-i)}})(e,n/t))},n.copy=function(){return t(r).domain(e)},tj.O.apply(n,arguments)}},scaleSequentialSqrt:function(){return rK},scaleSequentialSymlog:function(){return function t(){var e=tH(rX());return e.copy=function(){return rG(e,t()).constant(e.constant())},tj.O.apply(e,arguments)}},scaleSqrt:function(){return t0},scaleSymlog:function(){return function t(){var e=tH(tw());return e.copy=function(){return tx(e,t()).constant(e.constant())},tj.o.apply(e,arguments)}},scaleThreshold:function(){return function t(){var e,r=[.5],n=[0,1],o=1;function i(t){return null!=t&&t<=t?n[P(r,t,0,o)]:e}return i.domain=function(t){return arguments.length?(o=Math.min((r=Array.from(t)).length,n.length-1),i):r.slice()},i.range=function(t){return arguments.length?(n=Array.from(t),o=Math.min(r.length,n.length-1),i):n.slice()},i.invertExtent=function(t){var e=n.indexOf(t);return[r[e-1],r[e]]},i.unknown=function(t){return arguments.length?(e=t,i):e},i.copy=function(){return t().domain(r).range(n).unknown(e)},tj.o.apply(i,arguments)}},scaleTime:function(){return rY},scaleUtc:function(){return rH},tickFormat:function(){return tD}});var f=r(55284);let p=Math.sqrt(50),h=Math.sqrt(10),d=Math.sqrt(2);function y(t,e,r){let n,o,i;let a=(e-t)/Math.max(0,r),u=Math.floor(Math.log10(a)),c=a/Math.pow(10,u),l=c>=p?10:c>=h?5:c>=d?2:1;return(u<0?(n=Math.round(t*(i=Math.pow(10,-u)/l)),o=Math.round(e*i),n/ie&&--o,i=-i):(n=Math.round(t/(i=Math.pow(10,u)*l)),o=Math.round(e/i),n*ie&&--o),o0))return[];if(t===e)return[t];let n=e=o))return[];let u=i-o+1,c=Array(u);if(n){if(a<0)for(let t=0;te?1:t>=e?0:NaN}function x(t,e){return null==t||null==e?NaN:et?1:e>=t?0:NaN}function w(t){let e,r,n;function o(t,n,o=0,i=t.length){if(o>>1;0>r(t[e],n)?o=e+1:i=e}while(og(t(e),r),n=(e,r)=>t(e)-r):(e=t===g||t===x?t:O,r=t,n=t),{left:o,center:function(t,e,r=0,i=t.length){let a=o(t,e,r,i-1);return a>r&&n(t[a-1],e)>-n(t[a],e)?a-1:a},right:function(t,n,o=0,i=t.length){if(o>>1;0>=r(t[e],n)?o=e+1:i=e}while(o>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===r?Z(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===r?Z(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=N.exec(t))?new Y(e[1],e[2],e[3],1):(e=D.exec(t))?new Y(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=I.exec(t))?Z(e[1],e[2],e[3],e[4]):(e=L.exec(t))?Z(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=B.exec(t))?Q(e[1],e[2]/100,e[3]/100,1):(e=R.exec(t))?Q(e[1],e[2]/100,e[3]/100,e[4]):z.hasOwnProperty(t)?q(z[t]):"transparent"===t?new Y(NaN,NaN,NaN,0):null}function q(t){return new Y(t>>16&255,t>>8&255,255&t,1)}function Z(t,e,r,n){return n<=0&&(t=e=r=NaN),new Y(t,e,r,n)}function W(t,e,r,n){var o;return 1==arguments.length?((o=t)instanceof A||(o=$(o)),o)?new Y((o=o.rgb()).r,o.g,o.b,o.opacity):new Y:new Y(t,e,r,null==n?1:n)}function Y(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}function H(){return`#${K(this.r)}${K(this.g)}${K(this.b)}`}function X(){let t=G(this.opacity);return`${1===t?"rgb(":"rgba("}${V(this.r)}, ${V(this.g)}, ${V(this.b)}${1===t?")":`, ${t})`}`}function G(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function V(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function K(t){return((t=V(t))<16?"0":"")+t.toString(16)}function Q(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new tt(t,e,r,n)}function J(t){if(t instanceof tt)return new tt(t.h,t.s,t.l,t.opacity);if(t instanceof A||(t=$(t)),!t)return new tt;if(t instanceof tt)return t;var e=(t=t.rgb()).r/255,r=t.g/255,n=t.b/255,o=Math.min(e,r,n),i=Math.max(e,r,n),a=NaN,u=i-o,c=(i+o)/2;return u?(a=e===i?(r-n)/u+(r0&&c<1?0:a,new tt(a,u,c,t.opacity)}function tt(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}function te(t){return(t=(t||0)%360)<0?t+360:t}function tr(t){return Math.max(0,Math.min(1,t||0))}function tn(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}function to(t,e,r,n,o){var i=t*t,a=i*t;return((1-3*t+3*i-a)*e+(4-6*i+3*a)*r+(1+3*t+3*i-3*a)*n+a*o)/6}E(A,$,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:U,formatHex:U,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return J(this).formatHsl()},formatRgb:F,toString:F}),E(Y,W,k(A,{brighter(t){return t=null==t?1.4285714285714286:Math.pow(1.4285714285714286,t),new Y(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?.7:Math.pow(.7,t),new Y(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new Y(V(this.r),V(this.g),V(this.b),G(this.opacity))},displayable(){return -.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:H,formatHex:H,formatHex8:function(){return`#${K(this.r)}${K(this.g)}${K(this.b)}${K((isNaN(this.opacity)?1:this.opacity)*255)}`},formatRgb:X,toString:X})),E(tt,function(t,e,r,n){return 1==arguments.length?J(t):new tt(t,e,r,null==n?1:n)},k(A,{brighter(t){return t=null==t?1.4285714285714286:Math.pow(1.4285714285714286,t),new tt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?.7:Math.pow(.7,t),new tt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,o=2*r-n;return new Y(tn(t>=240?t-240:t+120,o,n),tn(t,o,n),tn(t<120?t+240:t-120,o,n),this.opacity)},clamp(){return new tt(te(this.h),tr(this.s),tr(this.l),G(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let t=G(this.opacity);return`${1===t?"hsl(":"hsla("}${te(this.h)}, ${100*tr(this.s)}%, ${100*tr(this.l)}%${1===t?")":`, ${t})`}`}}));var ti=t=>()=>t;function ta(t,e){var r=e-t;return r?function(e){return t+e*r}:ti(isNaN(t)?e:t)}var tu=function t(e){var r,n=1==(r=+(r=e))?ta:function(t,e){var n,o,i;return e-t?(n=t,o=e,n=Math.pow(n,i=r),o=Math.pow(o,i)-n,i=1/i,function(t){return Math.pow(n+t*o,i)}):ti(isNaN(t)?e:t)};function o(t,e){var r=n((t=W(t)).r,(e=W(e)).r),o=n(t.g,e.g),i=n(t.b,e.b),a=ta(t.opacity,e.opacity);return function(e){return t.r=r(e),t.g=o(e),t.b=i(e),t.opacity=a(e),t+""}}return o.gamma=t,o}(1);function tc(t){return function(e){var r,n,o=e.length,i=Array(o),a=Array(o),u=Array(o);for(r=0;r=1?(r=1,e-1):Math.floor(r*e),o=t[n],i=t[n+1],a=n>0?t[n-1]:2*o-i,u=nu&&(a=e.slice(u,a),l[c]?l[c]+=a:l[++c]=a),(o=o[0])===(i=i[0])?l[c]?l[c]+=i:l[++c]=i:(l[++c]=null,s.push({i:c,x:tl(o,i)})),u=tf.lastIndex;return ue&&(r=t,t=e,e=r),l=function(r){return Math.max(t,Math.min(e,r))}),n=c>2?tg:tb,o=i=null,f}function f(e){return null==e||isNaN(e=+e)?r:(o||(o=n(a.map(t),u,c)))(t(l(e)))}return f.invert=function(r){return l(e((i||(i=n(u,a.map(t),tl)))(r)))},f.domain=function(t){return arguments.length?(a=Array.from(t,td),s()):a.slice()},f.range=function(t){return arguments.length?(u=Array.from(t),s()):u.slice()},f.rangeRound=function(t){return u=Array.from(t),c=th,s()},f.clamp=function(t){return arguments.length?(l=!!t||tv,s()):l!==tv},f.interpolate=function(t){return arguments.length?(c=t,s()):c},f.unknown=function(t){return arguments.length?(r=t,f):r},function(r,n){return t=r,e=n,s()}}function tO(){return tw()(tv,tv)}var tj=r(89999),tS=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function tP(t){var e;if(!(e=tS.exec(t)))throw Error("invalid format: "+t);return new tE({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function tE(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function tk(t,e){if((r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var r,n=t.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+t.slice(r+1)]}function tA(t){return(t=tk(Math.abs(t)))?t[1]:NaN}function tM(t,e){var r=tk(t,e);if(!r)return t+"";var n=r[0],o=r[1];return o<0?"0."+Array(-o).join("0")+n:n.length>o+1?n.slice(0,o+1)+"."+n.slice(o+1):n+Array(o-n.length+2).join("0")}tP.prototype=tE.prototype,tE.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var t_={"%":(t,e)=>(100*t).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>tM(100*t,e),r:tM,s:function(t,e){var r=tk(t,e);if(!r)return t+"";var o=r[0],i=r[1],a=i-(n=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,u=o.length;return a===u?o:a>u?o+Array(a-u+1).join("0"):a>0?o.slice(0,a)+"."+o.slice(a):"0."+Array(1-a).join("0")+tk(t,Math.max(0,e+a-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function tT(t){return t}var tC=Array.prototype.map,tN=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"];function tD(t,e,r,n){var o,u,c=b(t,e,r);switch((n=tP(null==n?",f":n)).type){case"s":var l=Math.max(Math.abs(t),Math.abs(e));return null!=n.precision||isNaN(u=Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(tA(l)/3)))-tA(Math.abs(c))))||(n.precision=u),a(n,l);case"":case"e":case"g":case"p":case"r":null!=n.precision||isNaN(u=Math.max(0,tA(Math.abs(Math.max(Math.abs(t),Math.abs(e)))-(o=Math.abs(o=c)))-tA(o))+1)||(n.precision=u-("e"===n.type));break;case"f":case"%":null!=n.precision||isNaN(u=Math.max(0,-tA(Math.abs(c))))||(n.precision=u-("%"===n.type)*2)}return i(n)}function tI(t){var e=t.domain;return t.ticks=function(t){var r=e();return v(r[0],r[r.length-1],null==t?10:t)},t.tickFormat=function(t,r){var n=e();return tD(n[0],n[n.length-1],null==t?10:t,r)},t.nice=function(r){null==r&&(r=10);var n,o,i=e(),a=0,u=i.length-1,c=i[a],l=i[u],s=10;for(l0;){if((o=m(c,l,r))===n)return i[a]=c,i[u]=l,e(i);if(o>0)c=Math.floor(c/o)*o,l=Math.ceil(l/o)*o;else if(o<0)c=Math.ceil(c*o)/o,l=Math.floor(l*o)/o;else break;n=o}return t},t}function tL(){var t=tO();return t.copy=function(){return tx(t,tL())},tj.o.apply(t,arguments),tI(t)}function tB(t,e){t=t.slice();var r,n=0,o=t.length-1,i=t[n],a=t[o];return a-t(-e,r)}function tZ(t){let e,r;let n=t(tR,tz),o=n.domain,a=10;function u(){var i,u;return e=(i=a)===Math.E?Math.log:10===i&&Math.log10||2===i&&Math.log2||(i=Math.log(i),t=>Math.log(t)/i),r=10===(u=a)?t$:u===Math.E?Math.exp:t=>Math.pow(u,t),o()[0]<0?(e=tq(e),r=tq(r),t(tU,tF)):t(tR,tz),n}return n.base=function(t){return arguments.length?(a=+t,u()):a},n.domain=function(t){return arguments.length?(o(t),u()):o()},n.ticks=t=>{let n,i;let u=o(),c=u[0],l=u[u.length-1],s=l0){for(;f<=p;++f)for(n=1;nl)break;d.push(i)}}else for(;f<=p;++f)for(n=a-1;n>=1;--n)if(!((i=f>0?n/r(-f):n*r(f))l)break;d.push(i)}2*d.length{if(null==t&&(t=10),null==o&&(o=10===a?"s":","),"function"!=typeof o&&(a%1||null!=(o=tP(o)).precision||(o.trim=!0),o=i(o)),t===1/0)return o;let u=Math.max(1,a*t/n.ticks().length);return t=>{let n=t/r(Math.round(e(t)));return n*ao(tB(o(),{floor:t=>r(Math.floor(e(t))),ceil:t=>r(Math.ceil(e(t)))})),n}function tW(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function tY(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function tH(t){var e=1,r=t(tW(1),tY(e));return r.constant=function(r){return arguments.length?t(tW(e=+r),tY(e)):e},tI(r)}i=(o=function(t){var e,r,o,i=void 0===t.grouping||void 0===t.thousands?tT:(e=tC.call(t.grouping,Number),r=t.thousands+"",function(t,n){for(var o=t.length,i=[],a=0,u=e[0],c=0;o>0&&u>0&&(c+u+1>n&&(u=Math.max(1,n-c)),i.push(t.substring(o-=u,o+u)),!((c+=u+1)>n));)u=e[a=(a+1)%e.length];return i.reverse().join(r)}),a=void 0===t.currency?"":t.currency[0]+"",u=void 0===t.currency?"":t.currency[1]+"",c=void 0===t.decimal?".":t.decimal+"",l=void 0===t.numerals?tT:(o=tC.call(t.numerals,String),function(t){return t.replace(/[0-9]/g,function(t){return o[+t]})}),s=void 0===t.percent?"%":t.percent+"",f=void 0===t.minus?"−":t.minus+"",p=void 0===t.nan?"NaN":t.nan+"";function h(t){var e=(t=tP(t)).fill,r=t.align,o=t.sign,h=t.symbol,d=t.zero,y=t.width,v=t.comma,m=t.precision,b=t.trim,g=t.type;"n"===g?(v=!0,g="g"):t_[g]||(void 0===m&&(m=12),b=!0,g="g"),(d||"0"===e&&"="===r)&&(d=!0,e="0",r="=");var x="$"===h?a:"#"===h&&/[boxX]/.test(g)?"0"+g.toLowerCase():"",w="$"===h?u:/[%p]/.test(g)?s:"",O=t_[g],j=/[defgprs%]/.test(g);function S(t){var a,u,s,h=x,S=w;if("c"===g)S=O(t)+S,t="";else{var P=(t=+t)<0||1/t<0;if(t=isNaN(t)?p:O(Math.abs(t),m),b&&(t=function(t){e:for(var e,r=t.length,n=1,o=-1;n0&&(o=0)}return o>0?t.slice(0,o)+t.slice(e+1):t}(t)),P&&0==+t&&"+"!==o&&(P=!1),h=(P?"("===o?o:f:"-"===o||"("===o?"":o)+h,S=("s"===g?tN[8+n/3]:"")+S+(P&&"("===o?")":""),j){for(a=-1,u=t.length;++a(s=t.charCodeAt(a))||s>57){S=(46===s?c+t.slice(a+1):t.slice(a))+S,t=t.slice(0,a);break}}}v&&!d&&(t=i(t,1/0));var E=h.length+t.length+S.length,k=E>1)+h+t+S+k.slice(E);break;default:t=k+h+t+S}return l(t)}return m=void 0===m?6:/[gprs]/.test(g)?Math.max(1,Math.min(21,m)):Math.max(0,Math.min(20,m)),S.toString=function(){return t+""},S}return{format:h,formatPrefix:function(t,e){var r=h(((t=tP(t)).type="f",t)),n=3*Math.max(-8,Math.min(8,Math.floor(tA(e)/3))),o=Math.pow(10,-n),i=tN[8+n/3];return function(t){return r(o*t)+i}}}}({thousands:",",grouping:[3],currency:["$",""]})).format,a=o.formatPrefix;var tX=r(36967);function tG(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function tV(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function tK(t){return t<0?-t*t:t*t}function tQ(t){var e=t(tv,tv),r=1;return e.exponent=function(e){return arguments.length?1==(r=+e)?t(tv,tv):.5===r?t(tV,tK):t(tG(r),tG(1/r)):r},tI(e)}function tJ(){var t=tQ(tw());return t.copy=function(){return tx(t,tJ()).exponent(t.exponent())},tj.o.apply(t,arguments),t}function t0(){return tJ.apply(null,arguments).exponent(.5)}function t1(t){return Math.sign(t)*t*t}function t2(t,e){let r;if(void 0===e)for(let e of t)null!=e&&(r=e)&&(r=e);else{let n=-1;for(let o of t)null!=(o=e(o,++n,t))&&(r=o)&&(r=o)}return r}function t5(t,e){let r;if(void 0===e)for(let e of t)null!=e&&(r>e||void 0===r&&e>=e)&&(r=e);else{let n=-1;for(let o of t)null!=(o=e(o,++n,t))&&(r>o||void 0===r&&o>=o)&&(r=o)}return r}function t6(t,e){return(null==t||!(t>=t))-(null==e||!(e>=e))||(te?1:0)}function t3(t,e,r){let n=t[e];t[e]=t[r],t[r]=n}let t7=new Date,t4=new Date;function t8(t,e,r,n){function o(e){return t(e=0==arguments.length?new Date:new Date(+e)),e}return o.floor=e=>(t(e=new Date(+e)),e),o.ceil=r=>(t(r=new Date(r-1)),e(r,1),t(r),r),o.round=t=>{let e=o(t),r=o.ceil(t);return t-e(e(t=new Date(+t),null==r?1:Math.floor(r)),t),o.range=(r,n,i)=>{let a;let u=[];if(r=o.ceil(r),i=null==i?1:Math.floor(i),!(r0))return u;do u.push(a=new Date(+r)),e(r,i),t(r);while(at8(e=>{if(e>=e)for(;t(e),!r(e);)e.setTime(e-1)},(t,n)=>{if(t>=t){if(n<0)for(;++n<=0;)for(;e(t,-1),!r(t););else for(;--n>=0;)for(;e(t,1),!r(t););}}),r&&(o.count=(e,n)=>(t7.setTime(+e),t4.setTime(+n),t(t7),t(t4),Math.floor(r(t7,t4))),o.every=t=>isFinite(t=Math.floor(t))&&t>0?t>1?o.filter(n?e=>n(e)%t==0:e=>o.count(0,e)%t==0):o:null),o}let t9=t8(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);t9.every=t=>isFinite(t=Math.floor(t))&&t>0?t>1?t8(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):t9:null,t9.range;let et=t8(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+1e3*e)},(t,e)=>(e-t)/1e3,t=>t.getUTCSeconds());et.range;let ee=t8(t=>{t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds())},(t,e)=>{t.setTime(+t+6e4*e)},(t,e)=>(e-t)/6e4,t=>t.getMinutes());ee.range;let er=t8(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+6e4*e)},(t,e)=>(e-t)/6e4,t=>t.getUTCMinutes());er.range;let en=t8(t=>{t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds()-6e4*t.getMinutes())},(t,e)=>{t.setTime(+t+36e5*e)},(t,e)=>(e-t)/36e5,t=>t.getHours());en.range;let eo=t8(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+36e5*e)},(t,e)=>(e-t)/36e5,t=>t.getUTCHours());eo.range;let ei=t8(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/864e5,t=>t.getDate()-1);ei.range;let ea=t8(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>t.getUTCDate()-1);ea.range;let eu=t8(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>Math.floor(t/864e5));function ec(t){return t8(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(t,e)=>{t.setDate(t.getDate()+7*e)},(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/6048e5)}eu.range;let el=ec(0),es=ec(1),ef=ec(2),ep=ec(3),eh=ec(4),ed=ec(5),ey=ec(6);function ev(t){return t8(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+7*e)},(t,e)=>(e-t)/6048e5)}el.range,es.range,ef.range,ep.range,eh.range,ed.range,ey.range;let em=ev(0),eb=ev(1),eg=ev(2),ex=ev(3),ew=ev(4),eO=ev(5),ej=ev(6);em.range,eb.range,eg.range,ex.range,ew.range,eO.range,ej.range;let eS=t8(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth());eS.range;let eP=t8(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth());eP.range;let eE=t8(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());eE.every=t=>isFinite(t=Math.floor(t))&&t>0?t8(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)}):null,eE.range;let ek=t8(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());function eA(t,e,r,n,o,i){let a=[[et,1,1e3],[et,5,5e3],[et,15,15e3],[et,30,3e4],[i,1,6e4],[i,5,3e5],[i,15,9e5],[i,30,18e5],[o,1,36e5],[o,3,108e5],[o,6,216e5],[o,12,432e5],[n,1,864e5],[n,2,1728e5],[r,1,6048e5],[e,1,2592e6],[e,3,7776e6],[t,1,31536e6]];function u(e,r,n){let o=Math.abs(r-e)/n,i=w(([,,t])=>t).right(a,o);if(i===a.length)return t.every(b(e/31536e6,r/31536e6,n));if(0===i)return t9.every(Math.max(b(e,r,n),1));let[u,c]=a[o/a[i-1][2]isFinite(t=Math.floor(t))&&t>0?t8(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)}):null,ek.range;let[eM,e_]=eA(ek,eP,em,eu,eo,er),[eT,eC]=eA(eE,eS,el,ei,en,ee);function eN(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function eD(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function eI(t,e,r){return{y:t,m:e,d:r,H:0,M:0,S:0,L:0}}var eL={"-":"",_:" ",0:"0"},eB=/^\s*\d+/,eR=/^%/,ez=/[\\^$*+?|[\]().{}]/g;function eU(t,e,r){var n=t<0?"-":"",o=(n?-t:t)+"",i=o.length;return n+(i[t.toLowerCase(),e]))}function eZ(t,e,r){var n=eB.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function eW(t,e,r){var n=eB.exec(e.slice(r,r+1));return n?(t.u=+n[0],r+n[0].length):-1}function eY(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.U=+n[0],r+n[0].length):-1}function eH(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.V=+n[0],r+n[0].length):-1}function eX(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.W=+n[0],r+n[0].length):-1}function eG(t,e,r){var n=eB.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function eV(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function eK(t,e,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(r,r+6));return n?(t.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function eQ(t,e,r){var n=eB.exec(e.slice(r,r+1));return n?(t.q=3*n[0]-3,r+n[0].length):-1}function eJ(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function e0(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function e1(t,e,r){var n=eB.exec(e.slice(r,r+3));return n?(t.m=0,t.d=+n[0],r+n[0].length):-1}function e2(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function e5(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function e6(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function e3(t,e,r){var n=eB.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function e7(t,e,r){var n=eB.exec(e.slice(r,r+6));return n?(t.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function e4(t,e,r){var n=eR.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function e8(t,e,r){var n=eB.exec(e.slice(r));return n?(t.Q=+n[0],r+n[0].length):-1}function e9(t,e,r){var n=eB.exec(e.slice(r));return n?(t.s=+n[0],r+n[0].length):-1}function rt(t,e){return eU(t.getDate(),e,2)}function re(t,e){return eU(t.getHours(),e,2)}function rr(t,e){return eU(t.getHours()%12||12,e,2)}function rn(t,e){return eU(1+ei.count(eE(t),t),e,3)}function ro(t,e){return eU(t.getMilliseconds(),e,3)}function ri(t,e){return ro(t,e)+"000"}function ra(t,e){return eU(t.getMonth()+1,e,2)}function ru(t,e){return eU(t.getMinutes(),e,2)}function rc(t,e){return eU(t.getSeconds(),e,2)}function rl(t){var e=t.getDay();return 0===e?7:e}function rs(t,e){return eU(el.count(eE(t)-1,t),e,2)}function rf(t){var e=t.getDay();return e>=4||0===e?eh(t):eh.ceil(t)}function rp(t,e){return t=rf(t),eU(eh.count(eE(t),t)+(4===eE(t).getDay()),e,2)}function rh(t){return t.getDay()}function rd(t,e){return eU(es.count(eE(t)-1,t),e,2)}function ry(t,e){return eU(t.getFullYear()%100,e,2)}function rv(t,e){return eU((t=rf(t)).getFullYear()%100,e,2)}function rm(t,e){return eU(t.getFullYear()%1e4,e,4)}function rb(t,e){var r=t.getDay();return eU((t=r>=4||0===r?eh(t):eh.ceil(t)).getFullYear()%1e4,e,4)}function rg(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+eU(e/60|0,"0",2)+eU(e%60,"0",2)}function rx(t,e){return eU(t.getUTCDate(),e,2)}function rw(t,e){return eU(t.getUTCHours(),e,2)}function rO(t,e){return eU(t.getUTCHours()%12||12,e,2)}function rj(t,e){return eU(1+ea.count(ek(t),t),e,3)}function rS(t,e){return eU(t.getUTCMilliseconds(),e,3)}function rP(t,e){return rS(t,e)+"000"}function rE(t,e){return eU(t.getUTCMonth()+1,e,2)}function rk(t,e){return eU(t.getUTCMinutes(),e,2)}function rA(t,e){return eU(t.getUTCSeconds(),e,2)}function rM(t){var e=t.getUTCDay();return 0===e?7:e}function r_(t,e){return eU(em.count(ek(t)-1,t),e,2)}function rT(t){var e=t.getUTCDay();return e>=4||0===e?ew(t):ew.ceil(t)}function rC(t,e){return t=rT(t),eU(ew.count(ek(t),t)+(4===ek(t).getUTCDay()),e,2)}function rN(t){return t.getUTCDay()}function rD(t,e){return eU(eb.count(ek(t)-1,t),e,2)}function rI(t,e){return eU(t.getUTCFullYear()%100,e,2)}function rL(t,e){return eU((t=rT(t)).getUTCFullYear()%100,e,2)}function rB(t,e){return eU(t.getUTCFullYear()%1e4,e,4)}function rR(t,e){var r=t.getUTCDay();return eU((t=r>=4||0===r?ew(t):ew.ceil(t)).getUTCFullYear()%1e4,e,4)}function rz(){return"+0000"}function rU(){return"%"}function rF(t){return+t}function r$(t){return Math.floor(+t/1e3)}function rq(t){return new Date(t)}function rZ(t){return t instanceof Date?+t:+new Date(+t)}function rW(t,e,r,n,o,i,a,u,c,l){var s=tO(),f=s.invert,p=s.domain,h=l(".%L"),d=l(":%S"),y=l("%I:%M"),v=l("%I %p"),m=l("%a %d"),b=l("%b %d"),g=l("%B"),x=l("%Y");function w(t){return(c(t)1)for(var r,n,o,i=1,a=t[e[0]],u=a.length;i=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:rF,s:r$,S:rc,u:rl,U:rs,V:rp,w:rh,W:rd,x:null,X:null,y:ry,Y:rm,Z:rg,"%":rU},x={a:function(t){return a[t.getUTCDay()]},A:function(t){return i[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:rx,e:rx,f:rP,g:rL,G:rR,H:rw,I:rO,j:rj,L:rS,m:rE,M:rk,p:function(t){return o[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:rF,s:r$,S:rA,u:rM,U:r_,V:rC,w:rN,W:rD,x:null,X:null,y:rI,Y:rB,Z:rz,"%":rU},w={a:function(t,e,r){var n=h.exec(e.slice(r));return n?(t.w=d.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){var n=f.exec(e.slice(r));return n?(t.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){var n=m.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){var n=y.exec(e.slice(r));return n?(t.m=v.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,r,n){return S(t,e,r,n)},d:e0,e:e0,f:e7,g:eV,G:eG,H:e2,I:e2,j:e1,L:e3,m:eJ,M:e5,p:function(t,e,r){var n=l.exec(e.slice(r));return n?(t.p=s.get(n[0].toLowerCase()),r+n[0].length):-1},q:eQ,Q:e8,s:e9,S:e6,u:eW,U:eY,V:eH,w:eZ,W:eX,x:function(t,e,n){return S(t,r,e,n)},X:function(t,e,r){return S(t,n,e,r)},y:eV,Y:eG,Z:eK,"%":e4};function O(t,e){return function(r){var n,o,i,a=[],u=-1,c=0,l=t.length;for(r instanceof Date||(r=new Date(+r));++u53)return null;"w"in i||(i.w=1),"Z"in i?(n=(o=(n=eD(eI(i.y,0,1))).getUTCDay())>4||0===o?eb.ceil(n):eb(n),n=ea.offset(n,(i.V-1)*7),i.y=n.getUTCFullYear(),i.m=n.getUTCMonth(),i.d=n.getUTCDate()+(i.w+6)%7):(n=(o=(n=eN(eI(i.y,0,1))).getDay())>4||0===o?es.ceil(n):es(n),n=ei.offset(n,(i.V-1)*7),i.y=n.getFullYear(),i.m=n.getMonth(),i.d=n.getDate()+(i.w+6)%7)}else("W"in i||"U"in i)&&("w"in i||(i.w="u"in i?i.u%7:"W"in i?1:0),o="Z"in i?eD(eI(i.y,0,1)).getUTCDay():eN(eI(i.y,0,1)).getDay(),i.m=0,i.d="W"in i?(i.w+6)%7+7*i.W-(o+5)%7:i.w+7*i.U-(o+6)%7);return"Z"in i?(i.H+=i.Z/100|0,i.M+=i.Z%100,eD(i)):eN(i)}}function S(t,e,r,n){for(var o,i,a=0,u=e.length,c=r.length;a=c)return -1;if(37===(o=e.charCodeAt(a++))){if(!(i=w[(o=e.charAt(a++))in eL?e.charAt(a++):o])||(n=i(t,r,n))<0)return -1}else if(o!=r.charCodeAt(n++))return -1}return n}return g.x=O(r,g),g.X=O(n,g),g.c=O(e,g),x.x=O(r,x),x.X=O(n,x),x.c=O(e,x),{format:function(t){var e=O(t+="",g);return e.toString=function(){return t},e},parse:function(t){var e=j(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=O(t+="",x);return e.toString=function(){return t},e},utcParse:function(t){var e=j(t+="",!0);return e.toString=function(){return t},e}}}({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]})).format,u.parse,l=u.utcFormat,u.utcParse;var r2=r(22516),r5=r(76115);function r6(t){for(var e=t.length,r=Array(e);--e>=0;)r[e]=e;return r}function r3(t,e){return t[e]}function r7(t){let e=[];return e.key=t,e}var r4=r(95645),r8=r.n(r4),r9=r(99008),nt=r.n(r9),ne=r(77571),nr=r.n(ne),nn=r(86757),no=r.n(nn),ni=r(42715),na=r.n(ni),nu=r(13735),nc=r.n(nu),nl=r(11314),ns=r.n(nl),nf=r(82559),np=r.n(nf),nh=r(75551),nd=r.n(nh),ny=r(21652),nv=r.n(ny),nm=r(34935),nb=r.n(nm),ng=r(61134),nx=r.n(ng);function nw(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r=e?r.apply(void 0,o):t(e-a,nP(function(){for(var t=arguments.length,e=Array(t),n=0;nt.length)&&(e=t.length);for(var r=0,n=Array(e);rn&&(o=n,i=r),[o,i]}function nR(t,e,r){if(t.lte(0))return new(nx())(0);var n=nC.getDigitCount(t.toNumber()),o=new(nx())(10).pow(n),i=t.div(o),a=1!==n?.05:.1,u=new(nx())(Math.ceil(i.div(a).toNumber())).add(r).mul(a).mul(o);return e?u:new(nx())(Math.ceil(u))}function nz(t,e,r){var n=1,o=new(nx())(t);if(!o.isint()&&r){var i=Math.abs(t);i<1?(n=new(nx())(10).pow(nC.getDigitCount(t)-1),o=new(nx())(Math.floor(o.div(n).toNumber())).mul(n)):i>1&&(o=new(nx())(Math.floor(t)))}else 0===t?o=new(nx())(Math.floor((e-1)/2)):r||(o=new(nx())(Math.floor(t)));var a=Math.floor((e-1)/2);return nM(nA(function(t){return o.add(new(nx())(t-a).mul(n)).toNumber()}),nk)(0,e)}var nU=nT(function(t){var e=nD(t,2),r=e[0],n=e[1],o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6,i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],a=Math.max(o,2),u=nD(nB([r,n]),2),c=u[0],l=u[1];if(c===-1/0||l===1/0){var s=l===1/0?[c].concat(nN(nk(0,o-1).map(function(){return 1/0}))):[].concat(nN(nk(0,o-1).map(function(){return-1/0})),[l]);return r>n?n_(s):s}if(c===l)return nz(c,o,i);var f=function t(e,r,n,o){var i,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;if(!Number.isFinite((r-e)/(n-1)))return{step:new(nx())(0),tickMin:new(nx())(0),tickMax:new(nx())(0)};var u=nR(new(nx())(r).sub(e).div(n-1),o,a),c=Math.ceil((i=e<=0&&r>=0?new(nx())(0):(i=new(nx())(e).add(r).div(2)).sub(new(nx())(i).mod(u))).sub(e).div(u).toNumber()),l=Math.ceil(new(nx())(r).sub(i).div(u).toNumber()),s=c+l+1;return s>n?t(e,r,n,o,a+1):(s0?l+(n-s):l,c=r>0?c:c+(n-s)),{step:u,tickMin:i.sub(new(nx())(c).mul(u)),tickMax:i.add(new(nx())(l).mul(u))})}(c,l,a,i),p=f.step,h=f.tickMin,d=f.tickMax,y=nC.rangeStep(h,d.add(new(nx())(.1).mul(p)),p);return r>n?n_(y):y});nT(function(t){var e=nD(t,2),r=e[0],n=e[1],o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6,i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],a=Math.max(o,2),u=nD(nB([r,n]),2),c=u[0],l=u[1];if(c===-1/0||l===1/0)return[r,n];if(c===l)return nz(c,o,i);var s=nR(new(nx())(l).sub(c).div(a-1),i,0),f=nM(nA(function(t){return new(nx())(c).add(new(nx())(t).mul(s)).toNumber()}),nk)(0,a).filter(function(t){return t>=c&&t<=l});return r>n?n_(f):f});var nF=nT(function(t,e){var r=nD(t,2),n=r[0],o=r[1],i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],a=nD(nB([n,o]),2),u=a[0],c=a[1];if(u===-1/0||c===1/0)return[n,o];if(u===c)return[u];var l=nR(new(nx())(c).sub(u).div(Math.max(e,2)-1),i,0),s=[].concat(nN(nC.rangeStep(new(nx())(u),new(nx())(c).sub(new(nx())(.99).mul(l)),l)),[c]);return n>o?n_(s):s}),n$=r(13137),nq=r(16630),nZ=r(82944),nW=r(38569);function nY(t){return(nY="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function nH(t){return function(t){if(Array.isArray(t))return nX(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return nX(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return nX(t,void 0)}}(t)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function nX(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0,o=arguments.length>3?arguments[3]:void 0,i=-1,a=null!==(e=null==r?void 0:r.length)&&void 0!==e?e:0;if(a<=1)return 0;if(o&&"angleAxis"===o.axisType&&1e-6>=Math.abs(Math.abs(o.range[1]-o.range[0])-360))for(var u=o.range,c=0;c0?n[c-1].coordinate:n[a-1].coordinate,s=n[c].coordinate,f=c>=a-1?n[0].coordinate:n[c+1].coordinate,p=void 0;if((0,nq.uY)(s-l)!==(0,nq.uY)(f-s)){var h=[];if((0,nq.uY)(f-s)===(0,nq.uY)(u[1]-u[0])){p=f;var d=s+u[1]-u[0];h[0]=Math.min(d,(d+l)/2),h[1]=Math.max(d,(d+l)/2)}else{p=l;var y=f+u[1]-u[0];h[0]=Math.min(s,(y+s)/2),h[1]=Math.max(s,(y+s)/2)}var v=[Math.min(s,(p+s)/2),Math.max(s,(p+s)/2)];if(t>v[0]&&t<=v[1]||t>=h[0]&&t<=h[1]){i=n[c].index;break}}else{var m=Math.min(l,f),b=Math.max(l,f);if(t>(m+s)/2&&t<=(b+s)/2){i=n[c].index;break}}}else for(var g=0;g0&&g(r[g].coordinate+r[g-1].coordinate)/2&&t<=(r[g].coordinate+r[g+1].coordinate)/2||g===a-1&&t>(r[g].coordinate+r[g-1].coordinate)/2){i=r[g].index;break}return i},n1=function(t){var e,r,n=t.type.displayName,o=null!==(e=t.type)&&void 0!==e&&e.defaultProps?nV(nV({},t.type.defaultProps),t.props):t.props,i=o.stroke,a=o.fill;switch(n){case"Line":r=i;break;case"Area":case"Radar":r=i&&"none"!==i?i:a;break;default:r=a}return r},n2=function(t){var e=t.barSize,r=t.totalSize,n=t.stackGroups,o=void 0===n?{}:n;if(!o)return{};for(var i={},a=Object.keys(o),u=0,c=a.length;u=0});if(v&&v.length){var m=v[0].type.defaultProps,b=void 0!==m?nV(nV({},m),v[0].props):v[0].props,g=b.barSize,x=b[y];i[x]||(i[x]=[]);var w=nr()(g)?e:g;i[x].push({item:v[0],stackList:v.slice(1),barSize:nr()(w)?void 0:(0,nq.h1)(w,r,0)})}}return i},n5=function(t){var e,r=t.barGap,n=t.barCategoryGap,o=t.bandSize,i=t.sizeList,a=void 0===i?[]:i,u=t.maxBarSize,c=a.length;if(c<1)return null;var l=(0,nq.h1)(r,o,0,!0),s=[];if(a[0].barSize===+a[0].barSize){var f=!1,p=o/c,h=a.reduce(function(t,e){return t+e.barSize||0},0);(h+=(c-1)*l)>=o&&(h-=(c-1)*l,l=0),h>=o&&p>0&&(f=!0,p*=.9,h=c*p);var d={offset:((o-h)/2>>0)-l,size:0};e=a.reduce(function(t,e){var r={item:e.item,position:{offset:d.offset+d.size+l,size:f?p:e.barSize}},n=[].concat(nH(t),[r]);return d=n[n.length-1].position,e.stackList&&e.stackList.length&&e.stackList.forEach(function(t){n.push({item:t,position:d})}),n},s)}else{var y=(0,nq.h1)(n,o,0,!0);o-2*y-(c-1)*l<=0&&(l=0);var v=(o-2*y-(c-1)*l)/c;v>1&&(v>>=0);var m=u===+u?Math.min(v,u):v;e=a.reduce(function(t,e,r){var n=[].concat(nH(t),[{item:e.item,position:{offset:y+(v+l)*r+(v-m)/2,size:m}}]);return e.stackList&&e.stackList.length&&e.stackList.forEach(function(t){n.push({item:t,position:n[n.length-1].position})}),n},s)}return e},n6=function(t,e,r,n){var o=r.children,i=r.width,a=r.margin,u=i-(a.left||0)-(a.right||0),c=(0,nW.z)({children:o,legendWidth:u});if(c){var l=n||{},s=l.width,f=l.height,p=c.align,h=c.verticalAlign,d=c.layout;if(("vertical"===d||"horizontal"===d&&"middle"===h)&&"center"!==p&&(0,nq.hj)(t[p]))return nV(nV({},t),{},nK({},p,t[p]+(s||0)));if(("horizontal"===d||"vertical"===d&&"center"===p)&&"middle"!==h&&(0,nq.hj)(t[h]))return nV(nV({},t),{},nK({},h,t[h]+(f||0)))}return t},n3=function(t,e,r,n,o){var i=e.props.children,a=(0,nZ.NN)(i,n$.W).filter(function(t){var e;return e=t.props.direction,!!nr()(o)||("horizontal"===n?"yAxis"===o:"vertical"===n||"x"===e?"xAxis"===o:"y"!==e||"yAxis"===o)});if(a&&a.length){var u=a.map(function(t){return t.props.dataKey});return t.reduce(function(t,e){var n=nQ(e,r);if(nr()(n))return t;var o=Array.isArray(n)?[nt()(n),r8()(n)]:[n,n],i=u.reduce(function(t,r){var n=nQ(e,r,0),i=o[0]-Math.abs(Array.isArray(n)?n[0]:n),a=o[1]+Math.abs(Array.isArray(n)?n[1]:n);return[Math.min(i,t[0]),Math.max(a,t[1])]},[1/0,-1/0]);return[Math.min(i[0],t[0]),Math.max(i[1],t[1])]},[1/0,-1/0])}return null},n7=function(t,e,r,n,o){var i=e.map(function(e){return n3(t,e,r,o,n)}).filter(function(t){return!nr()(t)});return i&&i.length?i.reduce(function(t,e){return[Math.min(t[0],e[0]),Math.max(t[1],e[1])]},[1/0,-1/0]):null},n4=function(t,e,r,n,o){var i=e.map(function(e){var i=e.props.dataKey;return"number"===r&&i&&n3(t,e,i,n)||nJ(t,i,r,o)});if("number"===r)return i.reduce(function(t,e){return[Math.min(t[0],e[0]),Math.max(t[1],e[1])]},[1/0,-1/0]);var a={};return i.reduce(function(t,e){for(var r=0,n=e.length;r=2?2*(0,nq.uY)(a[0]-a[1])*c:c,e&&(t.ticks||t.niceTicks))?(t.ticks||t.niceTicks).map(function(t){return{coordinate:n(o?o.indexOf(t):t)+c,value:t,offset:c}}).filter(function(t){return!np()(t.coordinate)}):t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(t,e){return{coordinate:n(t)+c,value:t,index:e,offset:c}}):n.ticks&&!r?n.ticks(t.tickCount).map(function(t){return{coordinate:n(t)+c,value:t,offset:c}}):n.domain().map(function(t,e){return{coordinate:n(t)+c,value:o?o[t]:t,index:e,offset:c}})},oe=new WeakMap,or=function(t,e){if("function"!=typeof e)return t;oe.has(t)||oe.set(t,new WeakMap);var r=oe.get(t);if(r.has(e))return r.get(e);var n=function(){t.apply(void 0,arguments),e.apply(void 0,arguments)};return r.set(e,n),n},on=function(t,e,r){var n=t.scale,o=t.type,i=t.layout,a=t.axisType;if("auto"===n)return"radial"===i&&"radiusAxis"===a?{scale:f.Z(),realScaleType:"band"}:"radial"===i&&"angleAxis"===a?{scale:tL(),realScaleType:"linear"}:"category"===o&&e&&(e.indexOf("LineChart")>=0||e.indexOf("AreaChart")>=0||e.indexOf("ComposedChart")>=0&&!r)?{scale:f.x(),realScaleType:"point"}:"category"===o?{scale:f.Z(),realScaleType:"band"}:{scale:tL(),realScaleType:"linear"};if(na()(n)){var u="scale".concat(nd()(n));return{scale:(s[u]||f.x)(),realScaleType:s[u]?u:"point"}}return no()(n)?{scale:n}:{scale:f.x(),realScaleType:"point"}},oo=function(t){var e=t.domain();if(e&&!(e.length<=2)){var r=e.length,n=t.range(),o=Math.min(n[0],n[1])-1e-4,i=Math.max(n[0],n[1])+1e-4,a=t(e[0]),u=t(e[r-1]);(ai||ui)&&t.domain([e[0],e[r-1]])}},oi=function(t,e){if(!t)return null;for(var r=0,n=t.length;rn)&&(o[1]=n),o[0]>n&&(o[0]=n),o[1]=0?(t[a][r][0]=o,t[a][r][1]=o+u,o=t[a][r][1]):(t[a][r][0]=i,t[a][r][1]=i+u,i=t[a][r][1])}},expand:function(t,e){if((n=t.length)>0){for(var r,n,o,i=0,a=t[0].length;i0){for(var r,n=0,o=t[e[0]],i=o.length;n0&&(n=(r=t[e[0]]).length)>0){for(var r,n,o,i=0,a=1;a=0?(t[i][r][0]=o,t[i][r][1]=o+a,o=t[i][r][1]):(t[i][r][0]=0,t[i][r][1]=0)}}},oc=function(t,e,r){var n=e.map(function(t){return t.props.dataKey}),o=ou[r];return(function(){var t=(0,r5.Z)([]),e=r6,r=r1,n=r3;function o(o){var i,a,u=Array.from(t.apply(this,arguments),r7),c=u.length,l=-1;for(let t of o)for(i=0,++l;i=0?0:o<0?o:n}return r[0]},od=function(t,e){var r,n=(null!==(r=t.type)&&void 0!==r&&r.defaultProps?nV(nV({},t.type.defaultProps),t.props):t.props).stackId;if((0,nq.P2)(n)){var o=e[n];if(o){var i=o.items.indexOf(t);return i>=0?o.stackedData[i]:null}}return null},oy=function(t,e,r){return Object.keys(t).reduce(function(n,o){var i=t[o].stackedData.reduce(function(t,n){var o=n.slice(e,r+1).reduce(function(t,e){return[nt()(e.concat([t[0]]).filter(nq.hj)),r8()(e.concat([t[1]]).filter(nq.hj))]},[1/0,-1/0]);return[Math.min(t[0],o[0]),Math.max(t[1],o[1])]},[1/0,-1/0]);return[Math.min(i[0],n[0]),Math.max(i[1],n[1])]},[1/0,-1/0]).map(function(t){return t===1/0||t===-1/0?0:t})},ov=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,om=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,ob=function(t,e,r){if(no()(t))return t(e,r);if(!Array.isArray(t))return e;var n=[];if((0,nq.hj)(t[0]))n[0]=r?t[0]:Math.min(t[0],e[0]);else if(ov.test(t[0])){var o=+ov.exec(t[0])[1];n[0]=e[0]-o}else no()(t[0])?n[0]=t[0](e[0]):n[0]=e[0];if((0,nq.hj)(t[1]))n[1]=r?t[1]:Math.max(t[1],e[1]);else if(om.test(t[1])){var i=+om.exec(t[1])[1];n[1]=e[1]+i}else no()(t[1])?n[1]=t[1](e[1]):n[1]=e[1];return n},og=function(t,e,r){if(t&&t.scale&&t.scale.bandwidth){var n=t.scale.bandwidth();if(!r||n>0)return n}if(t&&e&&e.length>=2){for(var o=nb()(e,function(t){return t.coordinate}),i=1/0,a=1,u=o.length;a1&&void 0!==arguments[1]?arguments[1]:{};if(null==t||n.x.isSsr)return{width:0,height:0};var o=(Object.keys(e=a({},r)).forEach(function(t){e[t]||delete e[t]}),e),i=JSON.stringify({text:t,copyStyle:o});if(u.widthCache[i])return u.widthCache[i];try{var s=document.getElementById(l);s||((s=document.createElement("span")).setAttribute("id",l),s.setAttribute("aria-hidden","true"),document.body.appendChild(s));var f=a(a({},c),o);Object.assign(s.style,f),s.textContent="".concat(t);var p=s.getBoundingClientRect(),h={width:p.width,height:p.height};return u.widthCache[i]=h,++u.cacheCount>2e3&&(u.cacheCount=0,u.widthCache={}),h}catch(t){return{width:0,height:0}}},f=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}}},16630:function(t,e,r){"use strict";r.d(e,{Ap:function(){return S},EL:function(){return g},Kt:function(){return w},P2:function(){return m},Rw:function(){return v},bv:function(){return O},fC:function(){return P},h1:function(){return x},hU:function(){return d},hj:function(){return y},k4:function(){return j},uY:function(){return h}});var n=r(42715),o=r.n(n),i=r(82559),a=r.n(i),u=r(13735),c=r.n(u),l=r(22345),s=r.n(l),f=r(77571),p=r.n(f),h=function(t){return 0===t?0:t>0?1:-1},d=function(t){return o()(t)&&t.indexOf("%")===t.length-1},y=function(t){return s()(t)&&!a()(t)},v=function(t){return p()(t)},m=function(t){return y(t)||o()(t)},b=0,g=function(t){var e=++b;return"".concat(t||"").concat(e)},x=function(t,e){var r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!y(t)&&!o()(t))return n;if(d(t)){var u=t.indexOf("%");r=e*parseFloat(t.slice(0,u))/100}else r=+t;return a()(r)&&(r=n),i&&r>e&&(r=e),r},w=function(t){if(!t)return null;var e=Object.keys(t);return e&&e.length?t[e[0]]:null},O=function(t){if(!Array.isArray(t))return!1;for(var e=t.length,r={},n=0;n2?r-2:0),o=2;ot.length)&&(e=t.length);for(var r=0,n=Array(e);r2&&void 0!==arguments[2]?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(r.left||0)-(r.right||0)),Math.abs(e-(r.top||0)-(r.bottom||0)))/2},b=function(t,e,r,n,i){var a=t.width,u=t.height,s=t.startAngle,f=t.endAngle,y=(0,c.h1)(t.cx,a,a/2),v=(0,c.h1)(t.cy,u,u/2),b=m(a,u,r),g=(0,c.h1)(t.innerRadius,b,0),x=(0,c.h1)(t.outerRadius,b,.8*b);return Object.keys(e).reduce(function(t,r){var a,u=e[r],c=u.domain,m=u.reversed;if(o()(u.range))"angleAxis"===n?a=[s,f]:"radiusAxis"===n&&(a=[g,x]),m&&(a=[a[1],a[0]]);else{var b,w=function(t){if(Array.isArray(t))return t}(b=a=u.range)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{for(i=(r=r.call(t)).next;!(c=(n=i.call(r)).done)&&(u.push(n.value),2!==u.length);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(b,2)||function(t,e){if(t){if("string"==typeof t)return d(t,2);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return d(t,2)}}(b,2)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}();s=w[0],f=w[1]}var O=(0,l.Hq)(u,i),j=O.realScaleType,S=O.scale;S.domain(c).range(a),(0,l.zF)(S);var P=(0,l.g$)(S,p(p({},u),{},{realScaleType:j})),E=p(p(p({},u),P),{},{range:a,radius:x,realScaleType:j,scale:S,cx:y,cy:v,innerRadius:g,outerRadius:x,startAngle:s,endAngle:f});return p(p({},t),{},h({},r,E))},{})},g=function(t,e){var r=t.x,n=t.y;return Math.sqrt(Math.pow(r-e.x,2)+Math.pow(n-e.y,2))},x=function(t,e){var r=t.x,n=t.y,o=e.cx,i=e.cy,a=g({x:r,y:n},{x:o,y:i});if(a<=0)return{radius:a};var u=Math.acos((r-o)/a);return n>i&&(u=2*Math.PI-u),{radius:a,angle:180*u/Math.PI,angleInRadian:u}},w=function(t){var e=t.startAngle,r=t.endAngle,n=Math.min(Math.floor(e/360),Math.floor(r/360));return{startAngle:e-360*n,endAngle:r-360*n}},O=function(t,e){var r,n=x({x:t.x,y:t.y},e),o=n.radius,i=n.angle,a=e.innerRadius,u=e.outerRadius;if(ou)return!1;if(0===o)return!0;var c=w(e),l=c.startAngle,s=c.endAngle,f=i;if(l<=s){for(;f>s;)f-=360;for(;f=l&&f<=s}else{for(;f>l;)f-=360;for(;f=s&&f<=l}return r?p(p({},e),{},{radius:o,angle:f+360*Math.min(Math.floor(e.startAngle/360),Math.floor(e.endAngle/360))}):null},j=function(t){return(0,i.isValidElement)(t)||u()(t)||"boolean"==typeof t?"":t.className}},82944:function(t,e,r){"use strict";r.d(e,{$R:function(){return R},Bh:function(){return B},Gf:function(){return j},L6:function(){return N},NN:function(){return k},TT:function(){return M},eu:function(){return L},jf:function(){return T},rL:function(){return D},sP:function(){return A}});var n=r(13735),o=r.n(n),i=r(77571),a=r.n(i),u=r(42715),c=r.n(u),l=r(86757),s=r.n(l),f=r(28302),p=r.n(f),h=r(2265),d=r(14326),y=r(16630),v=r(46485),m=r(41637),b=["children"],g=["children"];function x(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function w(t){return(w="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var O={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},j=function(t){return"string"==typeof t?t:t?t.displayName||t.name||"Component":""},S=null,P=null,E=function t(e){if(e===S&&Array.isArray(P))return P;var r=[];return h.Children.forEach(e,function(e){a()(e)||((0,d.isFragment)(e)?r=r.concat(t(e.props.children)):r.push(e))}),P=r,S=e,r};function k(t,e){var r=[],n=[];return n=Array.isArray(e)?e.map(function(t){return j(t)}):[j(e)],E(t).forEach(function(t){var e=o()(t,"type.displayName")||o()(t,"type.name");-1!==n.indexOf(e)&&r.push(t)}),r}function A(t,e){var r=k(t,e);return r&&r[0]}var M=function(t){if(!t||!t.props)return!1;var e=t.props,r=e.width,n=e.height;return!!(0,y.hj)(r)&&!(r<=0)&&!!(0,y.hj)(n)&&!(n<=0)},_=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],T=function(t){return t&&"object"===w(t)&&"clipDot"in t},C=function(t,e,r,n){var o,i=null!==(o=null===m.ry||void 0===m.ry?void 0:m.ry[n])&&void 0!==o?o:[];return e.startsWith("data-")||!s()(t)&&(n&&i.includes(e)||m.Yh.includes(e))||r&&m.nv.includes(e)},N=function(t,e,r){if(!t||"function"==typeof t||"boolean"==typeof t)return null;var n=t;if((0,h.isValidElement)(t)&&(n=t.props),!p()(n))return null;var o={};return Object.keys(n).forEach(function(t){var i;C(null===(i=n)||void 0===i?void 0:i[t],t,e,r)&&(o[t]=n[t])}),o},D=function t(e,r){if(e===r)return!0;var n=h.Children.count(e);if(n!==h.Children.count(r))return!1;if(0===n)return!0;if(1===n)return I(Array.isArray(e)?e[0]:e,Array.isArray(r)?r[0]:r);for(var o=0;o=0)r.push(t);else if(t){var i=j(t.type),a=e[i]||{},u=a.handler,l=a.once;if(u&&(!l||!n[i])){var s=u(t,i,o);r.push(s),n[i]=!0}}}),r},B=function(t){var e=t&&t.type;return e&&O[e]?O[e]:null},R=function(t,e){return E(e).indexOf(t)}},46485:function(t,e,r){"use strict";function n(t,e){for(var r in t)if(({}).hasOwnProperty.call(t,r)&&(!({}).hasOwnProperty.call(e,r)||t[r]!==e[r]))return!1;for(var n in e)if(({}).hasOwnProperty.call(e,n)&&!({}).hasOwnProperty.call(t,n))return!1;return!0}r.d(e,{w:function(){return n}})},38569:function(t,e,r){"use strict";r.d(e,{z:function(){return l}});var n=r(22190),o=r(85355),i=r(82944);function a(t){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function u(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function c(t){for(var e=1;e=0))throw Error(`invalid digits: ${t}`);if(e>15)return a;let r=10**e;return function(t){this._+=t[0];for(let e=1,n=t.length;e1e-6){if(Math.abs(f*c-l*s)>1e-6&&i){let h=r-a,d=o-u,y=c*c+l*l,v=Math.sqrt(y),m=Math.sqrt(p),b=i*Math.tan((n-Math.acos((y+p-(h*h+d*d))/(2*v*m)))/2),g=b/m,x=b/v;Math.abs(g-1)>1e-6&&this._append`L${t+g*s},${e+g*f}`,this._append`A${i},${i},0,0,${+(f*h>s*d)},${this._x1=t+x*c},${this._y1=e+x*l}`}else this._append`L${this._x1=t},${this._y1=e}`}}arc(t,e,r,a,u,c){if(t=+t,e=+e,c=!!c,(r=+r)<0)throw Error(`negative radius: ${r}`);let l=r*Math.cos(a),s=r*Math.sin(a),f=t+l,p=e+s,h=1^c,d=c?a-u:u-a;null===this._x1?this._append`M${f},${p}`:(Math.abs(this._x1-f)>1e-6||Math.abs(this._y1-p)>1e-6)&&this._append`L${f},${p}`,r&&(d<0&&(d=d%o+o),d>i?this._append`A${r},${r},0,1,${h},${t-l},${e-s}A${r},${r},0,1,${h},${this._x1=f},${this._y1=p}`:d>1e-6&&this._append`A${r},${r},0,${+(d>=n)},${h},${this._x1=t+r*Math.cos(u)},${this._y1=e+r*Math.sin(u)}`)}rect(t,e,r,n){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}h${r=+r}v${+n}h${-r}Z`}toString(){return this._}}function c(t){let e=3;return t.digits=function(r){if(!arguments.length)return e;if(null==r)e=null;else{let t=Math.floor(r);if(!(t>=0))throw RangeError(`invalid digits: ${r}`);e=t}return t},()=>new u(e)}u.prototype},59121:function(t,e,r){"use strict";r.d(e,{E:function(){return i}});var n=r(99649),o=r(63497);function i(t,e){let r=(0,n.Q)(t);return isNaN(e)?(0,o.L)(t,NaN):(e&&r.setDate(r.getDate()+e),r)}},31091:function(t,e,r){"use strict";r.d(e,{z:function(){return i}});var n=r(99649),o=r(63497);function i(t,e){let r=(0,n.Q)(t);if(isNaN(e))return(0,o.L)(t,NaN);if(!e)return r;let i=r.getDate(),a=(0,o.L)(t,r.getTime());return(a.setMonth(r.getMonth()+e+1,0),i>=a.getDate())?a:(r.setFullYear(a.getFullYear(),a.getMonth(),i),r)}},63497:function(t,e,r){"use strict";function n(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}r.d(e,{L:function(){return n}})},99649:function(t,e,r){"use strict";function n(t){let e=Object.prototype.toString.call(t);return t instanceof Date||"object"==typeof t&&"[object Date]"===e?new t.constructor(+t):new Date("number"==typeof t||"[object Number]"===e||"string"==typeof t||"[object String]"===e?t:NaN)}r.d(e,{Q:function(){return n}})},69398:function(t,e,r){"use strict";function n(t,e){if(!t)throw Error("Invariant failed")}r.d(e,{Z:function(){return n}})}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1108-8b678b0704cb239b.js b/litellm/proxy/_experimental/out/_next/static/chunks/1108-8b678b0704cb239b.js deleted file mode 100644 index 89c5291477d..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/1108-8b678b0704cb239b.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1108],{40278:function(t,e,r){"use strict";r.d(e,{Z:function(){return S}});var n=r(5853),o=r(7084),i=r(26898),a=r(13241),u=r(1153),c=r(2265),l=r(47625),s=r(93765),f=r(31699),p=r(97059),h=r(62994),d=r(25311),y=(0,s.z)({chartName:"BarChart",GraphicalChild:f.$,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:p.K},{axisType:"yAxis",AxisComp:h.B}],formatAxisMap:d.t9}),v=r(56940),m=r(26680),b=r(8147),g=r(22190),x=r(65278),w=r(98593),O=r(92666),j=r(32644);let S=c.forwardRef((t,e)=>{let{data:r=[],categories:s=[],index:d,colors:S=i.s,valueFormatter:P=u.Cj,layout:E="horizontal",stack:k=!1,relative:A=!1,startEndOnly:M=!1,animationDuration:_=900,showAnimation:T=!1,showXAxis:C=!0,showYAxis:N=!0,yAxisWidth:D=56,intervalType:I="equidistantPreserveStart",showTooltip:L=!0,showLegend:B=!0,showGridLines:R=!0,autoMinValue:z=!1,minValue:U,maxValue:F,allowDecimals:$=!0,noDataText:q,onValueChange:Z,enableLegendSlider:W=!1,customTooltip:Y,rotateLabelX:H,barCategoryGap:X,tickGap:G=5,xAxisLabel:V,yAxisLabel:K,className:Q,padding:J=C||N?{left:20,right:20}:{left:0,right:0}}=t,tt=(0,n._T)(t,["data","categories","index","colors","valueFormatter","layout","stack","relative","startEndOnly","animationDuration","showAnimation","showXAxis","showYAxis","yAxisWidth","intervalType","showTooltip","showLegend","showGridLines","autoMinValue","minValue","maxValue","allowDecimals","noDataText","onValueChange","enableLegendSlider","customTooltip","rotateLabelX","barCategoryGap","tickGap","xAxisLabel","yAxisLabel","className","padding"]),[te,tr]=(0,c.useState)(60),tn=(0,j.me)(s,S),[to,ti]=c.useState(void 0),[ta,tu]=(0,c.useState)(void 0),tc=!!Z;function tl(t,e,r){var n,o,i,a;r.stopPropagation(),Z&&((0,j.vZ)(to,Object.assign(Object.assign({},t.payload),{value:t.value}))?(tu(void 0),ti(void 0),null==Z||Z(null)):(tu(null===(o=null===(n=t.tooltipPayload)||void 0===n?void 0:n[0])||void 0===o?void 0:o.dataKey),ti(Object.assign(Object.assign({},t.payload),{value:t.value})),null==Z||Z(Object.assign({eventType:"bar",categoryClicked:null===(a=null===(i=t.tooltipPayload)||void 0===i?void 0:i[0])||void 0===a?void 0:a.dataKey},t.payload))))}let ts=(0,j.i4)(z,U,F);return c.createElement("div",Object.assign({ref:e,className:(0,a.q)("w-full h-80",Q)},tt),c.createElement(l.h,{className:"h-full w-full"},(null==r?void 0:r.length)?c.createElement(y,{barCategoryGap:X,data:r,stackOffset:k?"sign":A?"expand":"none",layout:"vertical"===E?"vertical":"horizontal",onClick:tc&&(ta||to)?()=>{ti(void 0),tu(void 0),null==Z||Z(null)}:void 0,margin:{bottom:V?30:void 0,left:K?20:void 0,right:K?5:void 0,top:5}},R?c.createElement(v.q,{className:(0,a.q)("stroke-1","stroke-tremor-border","dark:stroke-dark-tremor-border"),horizontal:"vertical"!==E,vertical:"vertical"===E}):null,"vertical"!==E?c.createElement(p.K,{padding:J,hide:!C,dataKey:d,interval:M?"preserveStartEnd":I,tick:{transform:"translate(0, 6)"},ticks:M?[r[0][d],r[r.length-1][d]]:void 0,fill:"",stroke:"",className:(0,a.q)("mt-4 text-tremor-label","fill-tremor-content","dark:fill-dark-tremor-content"),tickLine:!1,axisLine:!1,angle:null==H?void 0:H.angle,dy:null==H?void 0:H.verticalShift,height:null==H?void 0:H.xAxisHeight,minTickGap:G},V&&c.createElement(m._,{position:"insideBottom",offset:-20,className:"fill-tremor-content-emphasis text-tremor-default font-medium dark:fill-dark-tremor-content-emphasis"},V)):c.createElement(p.K,{hide:!C,type:"number",tick:{transform:"translate(-3, 0)"},domain:ts,fill:"",stroke:"",className:(0,a.q)("text-tremor-label","fill-tremor-content","dark:fill-dark-tremor-content"),tickLine:!1,axisLine:!1,tickFormatter:P,minTickGap:G,allowDecimals:$,angle:null==H?void 0:H.angle,dy:null==H?void 0:H.verticalShift,height:null==H?void 0:H.xAxisHeight},V&&c.createElement(m._,{position:"insideBottom",offset:-20,className:"fill-tremor-content-emphasis text-tremor-default font-medium dark:fill-dark-tremor-content-emphasis"},V)),"vertical"!==E?c.createElement(h.B,{width:D,hide:!N,axisLine:!1,tickLine:!1,type:"number",domain:ts,tick:{transform:"translate(-3, 0)"},fill:"",stroke:"",className:(0,a.q)("text-tremor-label","fill-tremor-content","dark:fill-dark-tremor-content"),tickFormatter:A?t=>"".concat((100*t).toString()," %"):P,allowDecimals:$},K&&c.createElement(m._,{position:"insideLeft",style:{textAnchor:"middle"},angle:-90,offset:-15,className:"fill-tremor-content-emphasis text-tremor-default font-medium dark:fill-dark-tremor-content-emphasis"},K)):c.createElement(h.B,{width:D,hide:!N,dataKey:d,axisLine:!1,tickLine:!1,ticks:M?[r[0][d],r[r.length-1][d]]:void 0,type:"category",interval:"preserveStartEnd",tick:{transform:"translate(0, 6)"},fill:"",stroke:"",className:(0,a.q)("text-tremor-label","fill-tremor-content","dark:fill-dark-tremor-content")},K&&c.createElement(m._,{position:"insideLeft",style:{textAnchor:"middle"},angle:-90,offset:-15,className:"fill-tremor-content-emphasis text-tremor-default font-medium dark:fill-dark-tremor-content-emphasis"},K)),c.createElement(b.u,{wrapperStyle:{outline:"none"},isAnimationActive:!1,cursor:{fill:"#d1d5db",opacity:"0.15"},content:L?t=>{let{active:e,payload:r,label:n}=t;return Y?c.createElement(Y,{payload:null==r?void 0:r.map(t=>{var e;return Object.assign(Object.assign({},t),{color:null!==(e=tn.get(t.dataKey))&&void 0!==e?e:o.fr.Gray})}),active:e,label:n}):c.createElement(w.ZP,{active:e,payload:r,label:n,valueFormatter:P,categoryColors:tn})}:c.createElement(c.Fragment,null),position:{y:0}}),B?c.createElement(g.D,{verticalAlign:"top",height:te,content:t=>{let{payload:e}=t;return(0,x.Z)({payload:e},tn,tr,ta,tc?t=>{tc&&(t!==ta||to?(tu(t),null==Z||Z({eventType:"category",categoryClicked:t})):(tu(void 0),null==Z||Z(null)),ti(void 0))}:void 0,W)}}):null,s.map(t=>{var e;return c.createElement(f.$,{className:(0,a.q)((0,u.bM)(null!==(e=tn.get(t))&&void 0!==e?e:o.fr.Gray,i.K.background).fillColor,Z?"cursor-pointer":""),key:t,name:t,type:"linear",stackId:k||A?"a":void 0,dataKey:t,fill:"",isAnimationActive:T,animationDuration:_,shape:t=>((t,e,r,n)=>{let{fillOpacity:o,name:i,payload:a,value:u}=t,{x:l,width:s,y:f,height:p}=t;return"horizontal"===n&&p<0?(f+=p,p=Math.abs(p)):"vertical"===n&&s<0&&(l+=s,s=Math.abs(s)),c.createElement("rect",{x:l,y:f,width:s,height:p,opacity:e||r&&r!==i?(0,j.vZ)(e,Object.assign(Object.assign({},a),{value:u}))?o:.3:o})})(t,to,ta,E),onClick:tl})})):c.createElement(O.Z,{noDataText:q})))});S.displayName="BarChart"},65278:function(t,e,r){"use strict";r.d(e,{Z:function(){return y}});var n=r(2265);let o=t=>{n.useEffect(()=>{let e=()=>{t()};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[t])};var i=r(5853),a=r(26898),u=r(13241),c=r(1153);let l=t=>{var e=(0,i._T)(t,[]);return n.createElement("svg",Object.assign({},e,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),n.createElement("path",{d:"M8 12L14 6V18L8 12Z"}))},s=t=>{var e=(0,i._T)(t,[]);return n.createElement("svg",Object.assign({},e,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),n.createElement("path",{d:"M16 12L10 18V6L16 12Z"}))},f=(0,c.fn)("Legend"),p=t=>{let{name:e,color:r,onClick:o,activeLegend:i}=t,l=!!o;return n.createElement("li",{className:(0,u.q)(f("legendItem"),"group inline-flex items-center px-2 py-0.5 rounded-tremor-small transition whitespace-nowrap",l?"cursor-pointer":"cursor-default","text-tremor-content",l?"hover:bg-tremor-background-subtle":"","dark:text-dark-tremor-content",l?"dark:hover:bg-dark-tremor-background-subtle":""),onClick:t=>{t.stopPropagation(),null==o||o(e,r)}},n.createElement("svg",{className:(0,u.q)("flex-none h-2 w-2 mr-1.5",(0,c.bM)(r,a.K.text).textColor,i&&i!==e?"opacity-40":"opacity-100"),fill:"currentColor",viewBox:"0 0 8 8"},n.createElement("circle",{cx:4,cy:4,r:4})),n.createElement("p",{className:(0,u.q)("whitespace-nowrap truncate text-tremor-default","text-tremor-content",l?"group-hover:text-tremor-content-emphasis":"","dark:text-dark-tremor-content",i&&i!==e?"opacity-40":"opacity-100",l?"dark:group-hover:text-dark-tremor-content-emphasis":"")},e))},h=t=>{let{icon:e,onClick:r,disabled:o}=t,[i,a]=n.useState(!1),c=n.useRef(null);return n.useEffect(()=>(i?c.current=setInterval(()=>{null==r||r()},300):clearInterval(c.current),()=>clearInterval(c.current)),[i,r]),(0,n.useEffect)(()=>{o&&(clearInterval(c.current),a(!1))},[o]),n.createElement("button",{type:"button",className:(0,u.q)(f("legendSliderButton"),"w-5 group inline-flex items-center truncate rounded-tremor-small transition",o?"cursor-not-allowed":"cursor-pointer",o?"text-tremor-content-subtle":"text-tremor-content hover:text-tremor-content-emphasis hover:bg-tremor-background-subtle",o?"dark:text-dark-tremor-subtle":"dark:text-dark-tremor dark:hover:text-tremor-content-emphasis dark:hover:bg-dark-tremor-background-subtle"),disabled:o,onClick:t=>{t.stopPropagation(),null==r||r()},onMouseDown:t=>{t.stopPropagation(),a(!0)},onMouseUp:t=>{t.stopPropagation(),a(!1)}},n.createElement(e,{className:"w-full"}))},d=n.forwardRef((t,e)=>{let{categories:r,colors:o=a.s,className:c,onClickLegendItem:d,activeLegend:y,enableLegendSlider:v=!1}=t,m=(0,i._T)(t,["categories","colors","className","onClickLegendItem","activeLegend","enableLegendSlider"]),b=n.useRef(null),g=n.useRef(null),[x,w]=n.useState(null),[O,j]=n.useState(null),S=n.useRef(null),P=(0,n.useCallback)(()=>{let t=null==b?void 0:b.current;t&&w({left:t.scrollLeft>0,right:t.scrollWidth-t.clientWidth>t.scrollLeft})},[w]),E=(0,n.useCallback)(t=>{var e,r;let n=null==b?void 0:b.current,o=null==g?void 0:g.current,i=null!==(e=null==n?void 0:n.clientWidth)&&void 0!==e?e:0,a=null!==(r=null==o?void 0:o.clientWidth)&&void 0!==r?r:0;n&&v&&(n.scrollTo({left:"left"===t?n.scrollLeft-i+a:n.scrollLeft+i-a,behavior:"smooth"}),setTimeout(()=>{P()},400))},[v,P]);n.useEffect(()=>{let t=t=>{"ArrowLeft"===t?E("left"):"ArrowRight"===t&&E("right")};return O?(t(O),S.current=setInterval(()=>{t(O)},300)):clearInterval(S.current),()=>clearInterval(S.current)},[O,E]);let k=t=>{t.stopPropagation(),"ArrowLeft"!==t.key&&"ArrowRight"!==t.key||(t.preventDefault(),j(t.key))},A=t=>{t.stopPropagation(),j(null)};return n.useEffect(()=>{let t=null==b?void 0:b.current;return v&&(P(),null==t||t.addEventListener("keydown",k),null==t||t.addEventListener("keyup",A)),()=>{null==t||t.removeEventListener("keydown",k),null==t||t.removeEventListener("keyup",A)}},[P,v]),n.createElement("ol",Object.assign({ref:e,className:(0,u.q)(f("root"),"relative overflow-hidden",c)},m),n.createElement("div",{ref:b,tabIndex:0,className:(0,u.q)("h-full flex",v?(null==x?void 0:x.right)||(null==x?void 0:x.left)?"pl-4 pr-12 items-center overflow-auto snap-mandatory [&::-webkit-scrollbar]:hidden [scrollbar-width:none]":"":"flex-wrap")},r.map((t,e)=>n.createElement(p,{key:"item-".concat(e),name:t,color:o[e%o.length],onClick:d,activeLegend:y}))),v&&((null==x?void 0:x.right)||(null==x?void 0:x.left))?n.createElement(n.Fragment,null,n.createElement("div",{className:(0,u.q)("bg-tremor-background","dark:bg-dark-tremor-background","absolute flex top-0 pr-1 bottom-0 right-0 items-center justify-center h-full"),ref:g},n.createElement(h,{icon:l,onClick:()=>{j(null),E("left")},disabled:!(null==x?void 0:x.left)}),n.createElement(h,{icon:s,onClick:()=>{j(null),E("right")},disabled:!(null==x?void 0:x.right)}))):null)});d.displayName="Legend";let y=(t,e,r,i,a,u)=>{let{payload:c}=t,l=(0,n.useRef)(null);o(()=>{var t,e;r((e=null===(t=l.current)||void 0===t?void 0:t.clientHeight)?Number(e)+20:60)});let s=c.filter(t=>"none"!==t.type);return n.createElement("div",{ref:l,className:"flex items-center justify-end"},n.createElement(d,{categories:s.map(t=>t.value),colors:s.map(t=>e.get(t.value)),onClickLegendItem:a,activeLegend:i,enableLegendSlider:u}))}},98593:function(t,e,r){"use strict";r.d(e,{$B:function(){return c},ZP:function(){return s},zX:function(){return l}});var n=r(2265),o=r(7084),i=r(26898),a=r(13241),u=r(1153);let c=t=>{let{children:e}=t;return n.createElement("div",{className:(0,a.q)("rounded-tremor-default text-tremor-default border","bg-tremor-background shadow-tremor-dropdown border-tremor-border","dark:bg-dark-tremor-background dark:shadow-dark-tremor-dropdown dark:border-dark-tremor-border")},e)},l=t=>{let{value:e,name:r,color:o}=t;return n.createElement("div",{className:"flex items-center justify-between space-x-8"},n.createElement("div",{className:"flex items-center space-x-2"},n.createElement("span",{className:(0,a.q)("shrink-0 rounded-tremor-full border-2 h-3 w-3","border-tremor-background shadow-tremor-card","dark:border-dark-tremor-background dark:shadow-dark-tremor-card",(0,u.bM)(o,i.K.background).bgColor)}),n.createElement("p",{className:(0,a.q)("text-right whitespace-nowrap","text-tremor-content","dark:text-dark-tremor-content")},r)),n.createElement("p",{className:(0,a.q)("font-medium tabular-nums text-right whitespace-nowrap","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis")},e))},s=t=>{let{active:e,payload:r,label:i,categoryColors:u,valueFormatter:s}=t;if(e&&r){let t=r.filter(t=>"none"!==t.type);return n.createElement(c,null,n.createElement("div",{className:(0,a.q)("border-tremor-border border-b px-4 py-2","dark:border-dark-tremor-border")},n.createElement("p",{className:(0,a.q)("font-medium","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis")},i)),n.createElement("div",{className:(0,a.q)("px-4 py-2 space-y-1")},t.map((t,e)=>{var r;let{value:i,name:a}=t;return n.createElement(l,{key:"id-".concat(e),value:s(i),name:a,color:null!==(r=u.get(a))&&void 0!==r?r:o.fr.Blue})})))}return null}},92666:function(t,e,r){"use strict";r.d(e,{Z:function(){return i}});var n=r(13241),o=r(2265);let i=t=>{let{className:e,noDataText:r="No data"}=t;return o.createElement("div",{className:(0,n.q)("flex items-center justify-center w-full h-full border border-dashed rounded-tremor-default","border-tremor-border","dark:border-dark-tremor-border",e)},o.createElement("p",{className:(0,n.q)("text-tremor-content text-tremor-default","dark:text-dark-tremor-content")},r))}},32644:function(t,e,r){"use strict";r.d(e,{FB:function(){return i},i4:function(){return o},me:function(){return n},vZ:function(){return function t(e,r){if(e===r)return!0;if("object"!=typeof e||"object"!=typeof r||null===e||null===r)return!1;let n=Object.keys(e),o=Object.keys(r);if(n.length!==o.length)return!1;for(let i of n)if(!o.includes(i)||!t(e[i],r[i]))return!1;return!0}}});let n=(t,e)=>{let r=new Map;return t.forEach((t,n)=>{r.set(t,e[n%e.length])}),r},o=(t,e,r)=>[t?"auto":null!=e?e:0,null!=r?r:"auto"];function i(t,e){let r=[];for(let n of t)if(Object.prototype.hasOwnProperty.call(n,e)&&(r.push(n[e]),r.length>1))return!1;return!0}},49804:function(t,e,r){"use strict";r.d(e,{Z:function(){return l}});var n=r(5853),o=r(13241),i=r(1153),a=r(2265),u=r(9496);let c=(0,i.fn)("Col"),l=a.forwardRef((t,e)=>{let{numColSpan:r=1,numColSpanSm:i,numColSpanMd:l,numColSpanLg:s,children:f,className:p}=t,h=(0,n._T)(t,["numColSpan","numColSpanSm","numColSpanMd","numColSpanLg","children","className"]),d=(t,e)=>t&&Object.keys(e).includes(String(t))?e[t]:"";return a.createElement("div",Object.assign({ref:e,className:(0,o.q)(c("root"),(()=>{let t=d(r,u.PT),e=d(i,u.SP),n=d(l,u.VS),a=d(s,u._w);return(0,o.q)(t,e,n,a)})(),p)},h),f)});l.displayName="Col"},97765:function(t,e,r){"use strict";r.d(e,{Z:function(){return c}});var n=r(5853),o=r(26898),i=r(13241),a=r(1153),u=r(2265);let c=u.forwardRef((t,e)=>{let{color:r,children:c,className:l}=t,s=(0,n._T)(t,["color","children","className"]);return u.createElement("p",Object.assign({ref:e,className:(0,i.q)(r?(0,a.bM)(r,o.K.lightText).textColor:"text-tremor-content-emphasis dark:text-dark-tremor-content-emphasis",l)},s),c)});c.displayName="Subtitle"},61134:function(t,e,r){var n;!function(o){"use strict";var i,a={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},u=!0,c="[DecimalError] ",l=c+"Invalid argument: ",s=c+"Exponent out of range: ",f=Math.floor,p=Math.pow,h=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,d=f(1286742750677284.5),y={};function v(t,e){var r,n,o,i,a,c,l,s,f=t.constructor,p=f.precision;if(!t.s||!e.s)return e.s||(e=new f(t)),u?E(e,p):e;if(l=t.d,s=e.d,a=t.e,o=e.e,l=l.slice(),i=a-o){for(i<0?(n=l,i=-i,c=s.length):(n=s,o=a,c=l.length),i>(c=(a=Math.ceil(p/7))>c?a+1:c+1)&&(i=c,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for((c=l.length)-(i=s.length)<0&&(i=c,n=s,s=l,l=n),r=0;i;)r=(l[--i]=l[i]+s[i]+r)/1e7|0,l[i]%=1e7;for(r&&(l.unshift(r),++o),c=l.length;0==l[--c];)l.pop();return e.d=l,e.e=o,u?E(e,p):e}function m(t,e,r){if(t!==~~t||tr)throw Error(l+t)}function b(t){var e,r,n,o=t.length-1,i="",a=t[0];if(o>0){for(i+=a,e=1;et.e^this.s<0?1:-1;for(e=0,r=(n=this.d.length)<(o=t.d.length)?n:o;et.d[e]^this.s<0?1:-1;return n===o?0:n>o^this.s<0?1:-1},y.decimalPlaces=y.dp=function(){var t=this.d.length-1,e=(t-this.e)*7;if(t=this.d[t])for(;t%10==0;t/=10)e--;return e<0?0:e},y.dividedBy=y.div=function(t){return g(this,new this.constructor(t))},y.dividedToIntegerBy=y.idiv=function(t){var e=this.constructor;return E(g(this,new e(t),0,1),e.precision)},y.equals=y.eq=function(t){return!this.cmp(t)},y.exponent=function(){return w(this)},y.greaterThan=y.gt=function(t){return this.cmp(t)>0},y.greaterThanOrEqualTo=y.gte=function(t){return this.cmp(t)>=0},y.isInteger=y.isint=function(){return this.e>this.d.length-2},y.isNegative=y.isneg=function(){return this.s<0},y.isPositive=y.ispos=function(){return this.s>0},y.isZero=function(){return 0===this.s},y.lessThan=y.lt=function(t){return 0>this.cmp(t)},y.lessThanOrEqualTo=y.lte=function(t){return 1>this.cmp(t)},y.logarithm=y.log=function(t){var e,r=this.constructor,n=r.precision,o=n+5;if(void 0===t)t=new r(10);else if((t=new r(t)).s<1||t.eq(i))throw Error(c+"NaN");if(this.s<1)throw Error(c+(this.s?"NaN":"-Infinity"));return this.eq(i)?new r(0):(u=!1,e=g(S(this,o),S(t,o),o),u=!0,E(e,n))},y.minus=y.sub=function(t){return t=new this.constructor(t),this.s==t.s?k(this,t):v(this,(t.s=-t.s,t))},y.modulo=y.mod=function(t){var e,r=this.constructor,n=r.precision;if(!(t=new r(t)).s)throw Error(c+"NaN");return this.s?(u=!1,e=g(this,t,0,1).times(t),u=!0,this.minus(e)):E(new r(this),n)},y.naturalExponential=y.exp=function(){return x(this)},y.naturalLogarithm=y.ln=function(){return S(this)},y.negated=y.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t},y.plus=y.add=function(t){return t=new this.constructor(t),this.s==t.s?v(this,t):k(this,(t.s=-t.s,t))},y.precision=y.sd=function(t){var e,r,n;if(void 0!==t&&!!t!==t&&1!==t&&0!==t)throw Error(l+t);if(e=w(this)+1,r=7*(n=this.d.length-1)+1,n=this.d[n]){for(;n%10==0;n/=10)r--;for(n=this.d[0];n>=10;n/=10)r++}return t&&e>r?e:r},y.squareRoot=y.sqrt=function(){var t,e,r,n,o,i,a,l=this.constructor;if(this.s<1){if(!this.s)return new l(0);throw Error(c+"NaN")}for(t=w(this),u=!1,0==(o=Math.sqrt(+this))||o==1/0?(((e=b(this.d)).length+t)%2==0&&(e+="0"),o=Math.sqrt(e),t=f((t+1)/2)-(t<0||t%2),n=new l(e=o==1/0?"5e"+t:(e=o.toExponential()).slice(0,e.indexOf("e")+1)+t)):n=new l(o.toString()),o=a=(r=l.precision)+3;;)if(n=(i=n).plus(g(this,i,a+2)).times(.5),b(i.d).slice(0,a)===(e=b(n.d)).slice(0,a)){if(e=e.slice(a-3,a+1),o==a&&"4999"==e){if(E(i,r+1,0),i.times(i).eq(this)){n=i;break}}else if("9999"!=e)break;a+=4}return u=!0,E(n,r)},y.times=y.mul=function(t){var e,r,n,o,i,a,c,l,s,f=this.constructor,p=this.d,h=(t=new f(t)).d;if(!this.s||!t.s)return new f(0);for(t.s*=this.s,r=this.e+t.e,(l=p.length)<(s=h.length)&&(i=p,p=h,h=i,a=l,l=s,s=a),i=[],n=a=l+s;n--;)i.push(0);for(n=s;--n>=0;){for(e=0,o=l+n;o>n;)c=i[o]+h[n]*p[o-n-1]+e,i[o--]=c%1e7|0,e=c/1e7|0;i[o]=(i[o]+e)%1e7|0}for(;!i[--a];)i.pop();return e?++r:i.shift(),t.d=i,t.e=r,u?E(t,f.precision):t},y.toDecimalPlaces=y.todp=function(t,e){var r=this,n=r.constructor;return(r=new n(r),void 0===t)?r:(m(t,0,1e9),void 0===e?e=n.rounding:m(e,0,8),E(r,t+w(r)+1,e))},y.toExponential=function(t,e){var r,n=this,o=n.constructor;return void 0===t?r=A(n,!0):(m(t,0,1e9),void 0===e?e=o.rounding:m(e,0,8),r=A(n=E(new o(n),t+1,e),!0,t+1)),r},y.toFixed=function(t,e){var r,n,o=this.constructor;return void 0===t?A(this):(m(t,0,1e9),void 0===e?e=o.rounding:m(e,0,8),r=A((n=E(new o(this),t+w(this)+1,e)).abs(),!1,t+w(n)+1),this.isneg()&&!this.isZero()?"-"+r:r)},y.toInteger=y.toint=function(){var t=this.constructor;return E(new t(this),w(this)+1,t.rounding)},y.toNumber=function(){return+this},y.toPower=y.pow=function(t){var e,r,n,o,a,l,s=this,p=s.constructor,h=+(t=new p(t));if(!t.s)return new p(i);if(!(s=new p(s)).s){if(t.s<1)throw Error(c+"Infinity");return s}if(s.eq(i))return s;if(n=p.precision,t.eq(i))return E(s,n);if(l=(e=t.e)>=(r=t.d.length-1),a=s.s,l){if((r=h<0?-h:h)<=9007199254740991){for(o=new p(i),e=Math.ceil(n/7+4),u=!1;r%2&&M((o=o.times(s)).d,e),0!==(r=f(r/2));)M((s=s.times(s)).d,e);return u=!0,t.s<0?new p(i).div(o):E(o,n)}}else if(a<0)throw Error(c+"NaN");return a=a<0&&1&t.d[Math.max(e,r)]?-1:1,s.s=1,u=!1,o=t.times(S(s,n+12)),u=!0,(o=x(o)).s=a,o},y.toPrecision=function(t,e){var r,n,o=this,i=o.constructor;return void 0===t?(r=w(o),n=A(o,r<=i.toExpNeg||r>=i.toExpPos)):(m(t,1,1e9),void 0===e?e=i.rounding:m(e,0,8),r=w(o=E(new i(o),t,e)),n=A(o,t<=r||r<=i.toExpNeg,t)),n},y.toSignificantDigits=y.tosd=function(t,e){var r=this.constructor;return void 0===t?(t=r.precision,e=r.rounding):(m(t,1,1e9),void 0===e?e=r.rounding:m(e,0,8)),E(new r(this),t,e)},y.toString=y.valueOf=y.val=y.toJSON=function(){var t=w(this),e=this.constructor;return A(this,t<=e.toExpNeg||t>=e.toExpPos)};var g=function(){function t(t,e){var r,n=0,o=t.length;for(t=t.slice();o--;)r=t[o]*e+n,t[o]=r%1e7|0,n=r/1e7|0;return n&&t.unshift(n),t}function e(t,e,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;oe[o]?1:-1;break}return i}function r(t,e,r){for(var n=0;r--;)t[r]-=n,n=t[r]1;)t.shift()}return function(n,o,i,a){var u,l,s,f,p,h,d,y,v,m,b,g,x,O,j,S,P,k,A=n.constructor,M=n.s==o.s?1:-1,_=n.d,T=o.d;if(!n.s)return new A(n);if(!o.s)throw Error(c+"Division by zero");for(s=0,l=n.e-o.e,P=T.length,j=_.length,y=(d=new A(M)).d=[];T[s]==(_[s]||0);)++s;if(T[s]>(_[s]||0)&&--l,(g=null==i?i=A.precision:a?i+(w(n)-w(o))+1:i)<0)return new A(0);if(g=g/7+2|0,s=0,1==P)for(f=0,T=T[0],g++;(s1&&(T=t(T,f),_=t(_,f),P=T.length,j=_.length),O=P,m=(v=_.slice(0,P)).length;m=1e7/2&&++S;do f=0,(u=e(T,v,P,m))<0?(b=v[0],P!=m&&(b=1e7*b+(v[1]||0)),(f=b/S|0)>1?(f>=1e7&&(f=1e7-1),h=(p=t(T,f)).length,m=v.length,1==(u=e(p,v,h,m))&&(f--,r(p,P16)throw Error(s+w(t));if(!t.s)return new h(i);for(null==e?(u=!1,c=d):c=e,a=new h(.03125);t.abs().gte(.1);)t=t.times(a),f+=5;for(c+=Math.log(p(2,f))/Math.LN10*2+5|0,r=n=o=new h(i),h.precision=c;;){if(n=E(n.times(t),c),r=r.times(++l),b((a=o.plus(g(n,r,c))).d).slice(0,c)===b(o.d).slice(0,c)){for(;f--;)o=E(o.times(o),c);return h.precision=d,null==e?(u=!0,E(o,d)):o}o=a}}function w(t){for(var e=7*t.e,r=t.d[0];r>=10;r/=10)e++;return e}function O(t,e,r){if(e>t.LN10.sd())throw u=!0,r&&(t.precision=r),Error(c+"LN10 precision limit exceeded");return E(new t(t.LN10),e)}function j(t){for(var e="";t--;)e+="0";return e}function S(t,e){var r,n,o,a,l,s,f,p,h,d=1,y=t,v=y.d,m=y.constructor,x=m.precision;if(y.s<1)throw Error(c+(y.s?"NaN":"-Infinity"));if(y.eq(i))return new m(0);if(null==e?(u=!1,p=x):p=e,y.eq(10))return null==e&&(u=!0),O(m,p);if(p+=10,m.precision=p,n=(r=b(v)).charAt(0),!(15e14>Math.abs(a=w(y))))return f=O(m,p+2,x).times(a+""),y=S(new m(n+"."+r.slice(1)),p-10).plus(f),m.precision=x,null==e?(u=!0,E(y,x)):y;for(;n<7&&1!=n||1==n&&r.charAt(1)>3;)n=(r=b((y=y.times(t)).d)).charAt(0),d++;for(a=w(y),n>1?(y=new m("0."+r),a++):y=new m(n+"."+r.slice(1)),s=l=y=g(y.minus(i),y.plus(i),p),h=E(y.times(y),p),o=3;;){if(l=E(l.times(h),p),b((f=s.plus(g(l,new m(o),p))).d).slice(0,p)===b(s.d).slice(0,p))return s=s.times(2),0!==a&&(s=s.plus(O(m,p+2,x).times(a+""))),s=g(s,new m(d),p),m.precision=x,null==e?(u=!0,E(s,x)):s;s=f,o+=2}}function P(t,e){var r,n,o;for((r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),n=0;48===e.charCodeAt(n);)++n;for(o=e.length;48===e.charCodeAt(o-1);)--o;if(e=e.slice(n,o)){if(o-=n,r=r-n-1,t.e=f(r/7),t.d=[],n=(r+1)%7,r<0&&(n+=7),nd||t.e<-d))throw Error(s+r)}else t.s=0,t.e=0,t.d=[0];return t}function E(t,e,r){var n,o,i,a,c,l,h,y,v=t.d;for(a=1,i=v[0];i>=10;i/=10)a++;if((n=e-a)<0)n+=7,o=e,h=v[y=0];else{if((y=Math.ceil((n+1)/7))>=(i=v.length))return t;for(a=1,h=i=v[y];i>=10;i/=10)a++;n%=7,o=n-7+a}if(void 0!==r&&(c=h/(i=p(10,a-o-1))%10|0,l=e<0||void 0!==v[y+1]||h%i,l=r<4?(c||l)&&(0==r||r==(t.s<0?3:2)):c>5||5==c&&(4==r||l||6==r&&(n>0?o>0?h/p(10,a-o):0:v[y-1])%10&1||r==(t.s<0?8:7))),e<1||!v[0])return l?(i=w(t),v.length=1,e=e-i-1,v[0]=p(10,(7-e%7)%7),t.e=f(-e/7)||0):(v.length=1,v[0]=t.e=t.s=0),t;if(0==n?(v.length=y,i=1,y--):(v.length=y+1,i=p(10,7-n),v[y]=o>0?(h/p(10,a-o)%p(10,o)|0)*i:0),l)for(;;){if(0==y){1e7==(v[0]+=i)&&(v[0]=1,++t.e);break}if(v[y]+=i,1e7!=v[y])break;v[y--]=0,i=1}for(n=v.length;0===v[--n];)v.pop();if(u&&(t.e>d||t.e<-d))throw Error(s+w(t));return t}function k(t,e){var r,n,o,i,a,c,l,s,f,p,h=t.constructor,d=h.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new h(t),u?E(e,d):e;if(l=t.d,p=e.d,n=e.e,s=t.e,l=l.slice(),a=s-n){for((f=a<0)?(r=l,a=-a,c=p.length):(r=p,n=s,c=l.length),a>(o=Math.max(Math.ceil(d/7),c)+2)&&(a=o,r.length=1),r.reverse(),o=a;o--;)r.push(0);r.reverse()}else{for((f=(o=l.length)<(c=p.length))&&(c=o),o=0;o0;--o)l[c++]=0;for(o=p.length;o>a;){if(l[--o]0?i=i.charAt(0)+"."+i.slice(1)+j(n):a>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(o<0?"e":"e+")+o):o<0?(i="0."+j(-o-1)+i,r&&(n=r-a)>0&&(i+=j(n))):o>=a?(i+=j(o+1-a),r&&(n=r-o-1)>0&&(i=i+"."+j(n))):((n=o+1)0&&(o+1===a&&(i+="."),i+=j(n))),t.s<0?"-"+i:i}function M(t,e){if(t.length>e)return t.length=e,!0}function _(t){if(!t||"object"!=typeof t)throw Error(c+"Object expected");var e,r,n,o=["precision",1,1e9,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(e=0;e=o[e+1]&&n<=o[e+2])this[r]=n;else throw Error(l+r+": "+n)}if(void 0!==(n=t[r="LN10"])){if(n==Math.LN10)this[r]=new this(n);else throw Error(l+r+": "+n)}return this}(a=function t(e){var r,n,o;function i(t){if(!(this instanceof i))return new i(t);if(this.constructor=i,t instanceof i){this.s=t.s,this.e=t.e,this.d=(t=t.d)?t.slice():t;return}if("number"==typeof t){if(0*t!=0)throw Error(l+t);if(t>0)this.s=1;else if(t<0)t=-t,this.s=-1;else{this.s=0,this.e=0,this.d=[0];return}if(t===~~t&&t<1e7){this.e=0,this.d=[t];return}return P(this,t.toString())}if("string"!=typeof t)throw Error(l+t);if(45===t.charCodeAt(0)?(t=t.slice(1),this.s=-1):this.s=1,h.test(t))P(this,t);else throw Error(l+t)}if(i.prototype=y,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=t,i.config=i.set=_,void 0===e&&(e={}),e)for(r=0,o=["precision","rounding","toExpNeg","toExpPos","LN10"];r-1}},56883:function(t){t.exports=function(t,e,r){for(var n=-1,o=null==t?0:t.length;++n0&&i(s)?r>1?t(s,r-1,i,a,u):n(u,s):a||(u[u.length]=s)}return u}},63321:function(t,e,r){var n=r(33023)();t.exports=n},98060:function(t,e,r){var n=r(63321),o=r(43228);t.exports=function(t,e){return t&&n(t,e,o)}},92167:function(t,e,r){var n=r(67906),o=r(70235);t.exports=function(t,e){e=n(e,t);for(var r=0,i=e.length;null!=t&&re}},93012:function(t){t.exports=function(t,e){return null!=t&&e in Object(t)}},47909:function(t,e,r){var n=r(8235),o=r(31953),i=r(35281);t.exports=function(t,e,r){return e==e?i(t,e,r):n(t,o,r)}},90370:function(t,e,r){var n=r(54506),o=r(10303);t.exports=function(t){return o(t)&&"[object Arguments]"==n(t)}},56318:function(t,e,r){var n=r(6791),o=r(10303);t.exports=function t(e,r,i,a,u){return e===r||(null!=e&&null!=r&&(o(e)||o(r))?n(e,r,i,a,t,u):e!=e&&r!=r)}},6791:function(t,e,r){var n=r(85885),o=r(97638),i=r(88030),a=r(64974),u=r(81690),c=r(25614),l=r(98051),s=r(9792),f="[object Arguments]",p="[object Array]",h="[object Object]",d=Object.prototype.hasOwnProperty;t.exports=function(t,e,r,y,v,m){var b=c(t),g=c(e),x=b?p:u(t),w=g?p:u(e);x=x==f?h:x,w=w==f?h:w;var O=x==h,j=w==h,S=x==w;if(S&&l(t)){if(!l(e))return!1;b=!0,O=!1}if(S&&!O)return m||(m=new n),b||s(t)?o(t,e,r,y,v,m):i(t,e,x,r,y,v,m);if(!(1&r)){var P=O&&d.call(t,"__wrapped__"),E=j&&d.call(e,"__wrapped__");if(P||E){var k=P?t.value():t,A=E?e.value():e;return m||(m=new n),v(k,A,r,y,m)}}return!!S&&(m||(m=new n),a(t,e,r,y,v,m))}},62538:function(t,e,r){var n=r(85885),o=r(56318);t.exports=function(t,e,r,i){var a=r.length,u=a,c=!i;if(null==t)return!u;for(t=Object(t);a--;){var l=r[a];if(c&&l[2]?l[1]!==t[l[0]]:!(l[0]in t))return!1}for(;++ao?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(o);++n=200){var y=e?null:u(t);if(y)return c(y);p=!1,s=a,d=new n}else d=e?[]:h;t:for(;++l=o?t:n(t,e,r)}},1536:function(t,e,r){var n=r(78371);t.exports=function(t,e){if(t!==e){var r=void 0!==t,o=null===t,i=t==t,a=n(t),u=void 0!==e,c=null===e,l=e==e,s=n(e);if(!c&&!s&&!a&&t>e||a&&u&&l&&!c&&!s||o&&u&&l||!r&&l||!i)return 1;if(!o&&!a&&!s&&t=c)return l;return l*("desc"==r[o]?-1:1)}}return t.index-e.index}},92077:function(t,e,r){var n=r(74288)["__core-js_shared__"];t.exports=n},97930:function(t,e,r){var n=r(5629);t.exports=function(t,e){return function(r,o){if(null==r)return r;if(!n(r))return t(r,o);for(var i=r.length,a=e?i:-1,u=Object(r);(e?a--:++a-1?u[c?e[l]:l]:void 0}}},35464:function(t,e,r){var n=r(19608),o=r(49639),i=r(175);t.exports=function(t){return function(e,r,a){return a&&"number"!=typeof a&&o(e,r,a)&&(r=a=void 0),e=i(e),void 0===r?(r=e,e=0):r=i(r),a=void 0===a?es))return!1;var p=c.get(t),h=c.get(e);if(p&&h)return p==e&&h==t;var d=-1,y=!0,v=2&r?new n:void 0;for(c.set(t,e),c.set(e,t);++d-1&&t%1==0&&t-1}},13368:function(t,e,r){var n=r(24457);t.exports=function(t,e){var r=this.__data__,o=n(r,t);return o<0?(++this.size,r.push([t,e])):r[o][1]=e,this}},38764:function(t,e,r){var n=r(9855),o=r(99078),i=r(88675);t.exports=function(){this.size=0,this.__data__={hash:new n,map:new(i||o),string:new n}}},78615:function(t,e,r){var n=r(1507);t.exports=function(t){var e=n(this,t).delete(t);return this.size-=e?1:0,e}},83391:function(t,e,r){var n=r(1507);t.exports=function(t){return n(this,t).get(t)}},53483:function(t,e,r){var n=r(1507);t.exports=function(t){return n(this,t).has(t)}},74724:function(t,e,r){var n=r(1507);t.exports=function(t,e){var r=n(this,t),o=r.size;return r.set(t,e),this.size+=r.size==o?0:1,this}},22523:function(t){t.exports=function(t){var e=-1,r=Array(t.size);return t.forEach(function(t,n){r[++e]=[n,t]}),r}},47073:function(t){t.exports=function(t,e){return function(r){return null!=r&&r[t]===e&&(void 0!==e||t in Object(r))}}},23787:function(t,e,r){var n=r(50967);t.exports=function(t){var e=n(t,function(t){return 500===r.size&&r.clear(),t}),r=e.cache;return e}},20453:function(t,e,r){var n=r(39866)(Object,"create");t.exports=n},77184:function(t,e,r){var n=r(45070)(Object.keys,Object);t.exports=n},39931:function(t,e,r){t=r.nmd(t);var n=r(17071),o=e&&!e.nodeType&&e,i=o&&t&&!t.nodeType&&t,a=i&&i.exports===o&&n.process,u=function(){try{var t=i&&i.require&&i.require("util").types;if(t)return t;return a&&a.binding&&a.binding("util")}catch(t){}}();t.exports=u},45070:function(t){t.exports=function(t,e){return function(r){return t(e(r))}}},49478:function(t,e,r){var n=r(60493),o=Math.max;t.exports=function(t,e,r){return e=o(void 0===e?t.length-1:e,0),function(){for(var i=arguments,a=-1,u=o(i.length-e,0),c=Array(u);++a0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}},84092:function(t,e,r){var n=r(99078);t.exports=function(){this.__data__=new n,this.size=0}},31663:function(t){t.exports=function(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}},69135:function(t){t.exports=function(t){return this.__data__.get(t)}},39552:function(t){t.exports=function(t){return this.__data__.has(t)}},63960:function(t,e,r){var n=r(99078),o=r(88675),i=r(76219);t.exports=function(t,e){var r=this.__data__;if(r instanceof n){var a=r.__data__;if(!o||a.length<199)return a.push([t,e]),this.size=++r.size,this;r=this.__data__=new i(a)}return r.set(t,e),this.size=r.size,this}},35281:function(t){t.exports=function(t,e,r){for(var n=r-1,o=t.length;++n-1&&t%1==0&&t<=9007199254740991}},82559:function(t,e,r){var n=r(22345);t.exports=function(t){return n(t)&&t!=+t}},77571:function(t){t.exports=function(t){return null==t}},22345:function(t,e,r){var n=r(54506),o=r(10303);t.exports=function(t){return"number"==typeof t||o(t)&&"[object Number]"==n(t)}},90231:function(t,e,r){var n=r(54506),o=r(62602),i=r(10303),a=Object.prototype,u=Function.prototype.toString,c=a.hasOwnProperty,l=u.call(Object);t.exports=function(t){if(!i(t)||"[object Object]"!=n(t))return!1;var e=o(t);if(null===e)return!0;var r=c.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&u.call(r)==l}},42715:function(t,e,r){var n=r(54506),o=r(25614),i=r(10303);t.exports=function(t){return"string"==typeof t||!o(t)&&i(t)&&"[object String]"==n(t)}},9792:function(t,e,r){var n=r(59332),o=r(23305),i=r(39931),a=i&&i.isTypedArray,u=a?o(a):n;t.exports=u},43228:function(t,e,r){var n=r(28579),o=r(4578),i=r(5629);t.exports=function(t){return i(t)?n(t):o(t)}},86185:function(t){t.exports=function(t){var e=null==t?0:t.length;return e?t[e-1]:void 0}},89238:function(t,e,r){var n=r(73819),o=r(88157),i=r(24240),a=r(25614);t.exports=function(t,e){return(a(t)?n:i)(t,o(e,3))}},41443:function(t,e,r){var n=r(83023),o=r(98060),i=r(88157);t.exports=function(t,e){var r={};return e=i(e,3),o(t,function(t,o,i){n(r,o,e(t,o,i))}),r}},95645:function(t,e,r){var n=r(67646),o=r(58905),i=r(79586);t.exports=function(t){return t&&t.length?n(t,i,o):void 0}},50967:function(t,e,r){var n=r(76219);function o(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw TypeError("Expected a function");var r=function(){var n=arguments,o=e?e.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var a=t.apply(this,n);return r.cache=i.set(o,a)||i,a};return r.cache=new(o.Cache||n),r}o.Cache=n,t.exports=o},99008:function(t,e,r){var n=r(67646),o=r(20121),i=r(79586);t.exports=function(t){return t&&t.length?n(t,i,o):void 0}},93810:function(t){t.exports=function(){}},22350:function(t,e,r){var n=r(18155),o=r(73584),i=r(67352),a=r(70235);t.exports=function(t){return i(t)?n(a(t)):o(t)}},99676:function(t,e,r){var n=r(35464)();t.exports=n},33645:function(t,e,r){var n=r(25253),o=r(88157),i=r(12327),a=r(25614),u=r(49639);t.exports=function(t,e,r){var c=a(t)?n:i;return r&&u(t,e,r)&&(e=void 0),c(t,o(e,3))}},34935:function(t,e,r){var n=r(72569),o=r(84046),i=r(44843),a=r(49639),u=i(function(t,e){if(null==t)return[];var r=e.length;return r>1&&a(t,e[0],e[1])?e=[]:r>2&&a(e[0],e[1],e[2])&&(e=[e[0]]),o(t,n(e,1),[])});t.exports=u},55716:function(t){t.exports=function(){return[]}},7406:function(t){t.exports=function(){return!1}},37065:function(t,e,r){var n=r(7310),o=r(28302);t.exports=function(t,e,r){var i=!0,a=!0;if("function"!=typeof t)throw TypeError("Expected a function");return o(r)&&(i="leading"in r?!!r.leading:i,a="trailing"in r?!!r.trailing:a),n(t,e,{leading:i,maxWait:e,trailing:a})}},175:function(t,e,r){var n=r(6660),o=1/0;t.exports=function(t){return t?(t=n(t))===o||t===-o?(t<0?-1:1)*17976931348623157e292:t==t?t:0:0===t?t:0}},85759:function(t,e,r){var n=r(175);t.exports=function(t){var e=n(t),r=e%1;return e==e?r?e-r:e:0}},3641:function(t,e,r){var n=r(65020);t.exports=function(t){return null==t?"":n(t)}},47230:function(t,e,r){var n=r(88157),o=r(13826);t.exports=function(t,e){return t&&t.length?o(t,n(e,2)):[]}},75551:function(t,e,r){var n=r(80675)("toUpperCase");t.exports=n},48049:function(t,e,r){"use strict";var n=r(14397);function o(){}function i(){}i.resetWarningCache=o,t.exports=function(){function t(t,e,r,o,i,a){if(a!==n){var u=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}function e(){return t}t.isRequired=t;var r={array:t,bigint:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,elementType:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e,checkPropTypes:i,resetWarningCache:o};return r.PropTypes=r,r}},40718:function(t,e,r){t.exports=r(48049)()},14397:function(t){"use strict";t.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},84735:function(t,e,r){"use strict";r.d(e,{ZP:function(){return tS}});var n=r(2265),o=r(40718),i=r.n(o),a=Object.getOwnPropertyNames,u=Object.getOwnPropertySymbols,c=Object.prototype.hasOwnProperty;function l(t,e){return function(r,n,o){return t(r,n,o)&&e(r,n,o)}}function s(t){return function(e,r,n){if(!e||!r||"object"!=typeof e||"object"!=typeof r)return t(e,r,n);var o=n.cache,i=o.get(e),a=o.get(r);if(i&&a)return i===r&&a===e;o.set(e,r),o.set(r,e);var u=t(e,r,n);return o.delete(e),o.delete(r),u}}function f(t){return a(t).concat(u(t))}var p=Object.hasOwn||function(t,e){return c.call(t,e)};function h(t,e){return t===e||!t&&!e&&t!=t&&e!=e}var d=Object.getOwnPropertyDescriptor,y=Object.keys;function v(t,e,r){var n=t.length;if(e.length!==n)return!1;for(;n-- >0;)if(!r.equals(t[n],e[n],n,n,t,e,r))return!1;return!0}function m(t,e){return h(t.getTime(),e.getTime())}function b(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function g(t,e){return t===e}function x(t,e,r){var n,o,i=t.size;if(i!==e.size)return!1;if(!i)return!0;for(var a=Array(i),u=t.entries(),c=0;(n=u.next())&&!n.done;){for(var l=e.entries(),s=!1,f=0;(o=l.next())&&!o.done;){if(a[f]){f++;continue}var p=n.value,h=o.value;if(r.equals(p[0],h[0],c,f,t,e,r)&&r.equals(p[1],h[1],p[0],h[0],t,e,r)){s=a[f]=!0;break}f++}if(!s)return!1;c++}return!0}function w(t,e,r){var n=y(t),o=n.length;if(y(e).length!==o)return!1;for(;o-- >0;)if(!A(t,e,r,n[o]))return!1;return!0}function O(t,e,r){var n,o,i,a=f(t),u=a.length;if(f(e).length!==u)return!1;for(;u-- >0;)if(!A(t,e,r,n=a[u])||(o=d(t,n),i=d(e,n),(o||i)&&(!o||!i||o.configurable!==i.configurable||o.enumerable!==i.enumerable||o.writable!==i.writable)))return!1;return!0}function j(t,e){return h(t.valueOf(),e.valueOf())}function S(t,e){return t.source===e.source&&t.flags===e.flags}function P(t,e,r){var n,o,i=t.size;if(i!==e.size)return!1;if(!i)return!0;for(var a=Array(i),u=t.values();(n=u.next())&&!n.done;){for(var c=e.values(),l=!1,s=0;(o=c.next())&&!o.done;){if(!a[s]&&r.equals(n.value,o.value,n.value,o.value,t,e,r)){l=a[s]=!0;break}s++}if(!l)return!1}return!0}function E(t,e){var r=t.length;if(e.length!==r)return!1;for(;r-- >0;)if(t[r]!==e[r])return!1;return!0}function k(t,e){return t.hostname===e.hostname&&t.pathname===e.pathname&&t.protocol===e.protocol&&t.port===e.port&&t.hash===e.hash&&t.username===e.username&&t.password===e.password}function A(t,e,r,n){return("_owner"===n||"__o"===n||"__v"===n)&&(!!t.$$typeof||!!e.$$typeof)||p(e,n)&&r.equals(t[n],e[n],n,n,t,e,r)}var M=Array.isArray,_="undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView:null,T=Object.assign,C=Object.prototype.toString.call.bind(Object.prototype.toString),N=D();function D(t){void 0===t&&(t={});var e,r,n,o,i,a,u,c,f,p,d,y,A,N,D=t.circular,I=t.createInternalComparator,L=t.createState,B=t.strict,R=(r=(e=function(t){var e=t.circular,r=t.createCustomConfig,n=t.strict,o={areArraysEqual:n?O:v,areDatesEqual:m,areErrorsEqual:b,areFunctionsEqual:g,areMapsEqual:n?l(x,O):x,areNumbersEqual:h,areObjectsEqual:n?O:w,arePrimitiveWrappersEqual:j,areRegExpsEqual:S,areSetsEqual:n?l(P,O):P,areTypedArraysEqual:n?O:E,areUrlsEqual:k,unknownTagComparators:void 0};if(r&&(o=T({},o,r(o))),e){var i=s(o.areArraysEqual),a=s(o.areMapsEqual),u=s(o.areObjectsEqual),c=s(o.areSetsEqual);o=T({},o,{areArraysEqual:i,areMapsEqual:a,areObjectsEqual:u,areSetsEqual:c})}return o}(t)).areArraysEqual,n=e.areDatesEqual,o=e.areErrorsEqual,i=e.areFunctionsEqual,a=e.areMapsEqual,u=e.areNumbersEqual,c=e.areObjectsEqual,f=e.arePrimitiveWrappersEqual,p=e.areRegExpsEqual,d=e.areSetsEqual,y=e.areTypedArraysEqual,A=e.areUrlsEqual,N=e.unknownTagComparators,function(t,e,l){if(t===e)return!0;if(null==t||null==e)return!1;var s=typeof t;if(s!==typeof e)return!1;if("object"!==s)return"number"===s?u(t,e,l):"function"===s&&i(t,e,l);var h=t.constructor;if(h!==e.constructor)return!1;if(h===Object)return c(t,e,l);if(M(t))return r(t,e,l);if(null!=_&&_(t))return y(t,e,l);if(h===Date)return n(t,e,l);if(h===RegExp)return p(t,e,l);if(h===Map)return a(t,e,l);if(h===Set)return d(t,e,l);var v=C(t);if("[object Date]"===v)return n(t,e,l);if("[object RegExp]"===v)return p(t,e,l);if("[object Map]"===v)return a(t,e,l);if("[object Set]"===v)return d(t,e,l);if("[object Object]"===v)return"function"!=typeof t.then&&"function"!=typeof e.then&&c(t,e,l);if("[object URL]"===v)return A(t,e,l);if("[object Error]"===v)return o(t,e,l);if("[object Arguments]"===v)return c(t,e,l);if("[object Boolean]"===v||"[object Number]"===v||"[object String]"===v)return f(t,e,l);if(N){var m=N[v];if(!m){var b=null!=t?t[Symbol.toStringTag]:void 0;b&&(m=N[b])}if(m)return m(t,e,l)}return!1}),z=I?I(R):function(t,e,r,n,o,i,a){return R(t,e,a)};return function(t){var e=t.circular,r=t.comparator,n=t.createState,o=t.equals,i=t.strict;if(n)return function(t,a){var u=n(),c=u.cache;return r(t,a,{cache:void 0===c?e?new WeakMap:void 0:c,equals:o,meta:u.meta,strict:i})};if(e)return function(t,e){return r(t,e,{cache:new WeakMap,equals:o,meta:void 0,strict:i})};var a={cache:void 0,equals:o,meta:void 0,strict:i};return function(t,e){return r(t,e,a)}}({circular:void 0!==D&&D,comparator:R,createState:L,equals:z,strict:void 0!==B&&B})}function I(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=-1;requestAnimationFrame(function n(o){if(r<0&&(r=o),o-r>e)t(o),r=-1;else{var i;i=n,"undefined"!=typeof requestAnimationFrame&&requestAnimationFrame(i)}})}function L(t){return(L="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function B(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);rt.length)&&(e=t.length);for(var r=0,n=Array(e);r=0&&t<=1}),"[configBezier]: arguments should be x1, y1, x2, y2 of [0, 1] instead received %s",n);var p=V(i,u),h=V(a,c),d=(t=i,e=u,function(r){var n;return G([].concat(function(t){if(Array.isArray(t))return H(t)}(n=X(t,e).map(function(t,e){return t*e}).slice(1))||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(n)||Y(n)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(),[0]),r)}),y=function(t){for(var e=t>1?1:t,r=e,n=0;n<8;++n){var o,i=p(r)-e,a=d(r);if(1e-4>Math.abs(i-e)||a<1e-4)break;r=(o=r-i/a)>1?1:o<0?0:o}return h(r)};return y.isStepper=!1,y},Q=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.stiff,r=void 0===e?100:e,n=t.damping,o=void 0===n?8:n,i=t.dt,a=void 0===i?17:i,u=function(t,e,n){var i=n+(-(t-e)*r-n*o)*a/1e3,u=n*a/1e3+t;return 1e-4>Math.abs(u-e)&&1e-4>Math.abs(i)?[e,0]:[u,i]};return u.isStepper=!0,u.dt=a,u},J=function(){for(var t=arguments.length,e=Array(t),r=0;rt.length)&&(e=t.length);for(var r=0,n=Array(e);rt.length)&&(e=t.length);for(var r=0,n=Array(e);r0?r[o-1]:n,p=l||Object.keys(c);if("function"==typeof u||"spring"===u)return[].concat(th(t),[e.runJSAnimation.bind(e,{from:f.style,to:c,duration:i,easing:u}),i]);var h=Z(p,i,u),d=tv(tv(tv({},f.style),c),{},{transition:h});return[].concat(th(t),[d,i,s]).filter($)},[a,Math.max(void 0===u?0:u,n)])),[t.onAnimationEnd]))}},{key:"runAnimation",value:function(t){if(!this.manager){var e,r,n;this.manager=(e=function(){return null},r=!1,n=function t(n){if(!r){if(Array.isArray(n)){if(!n.length)return;var o=function(t){if(Array.isArray(t))return t}(n)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(n)||function(t,e){if(t){if("string"==typeof t)return B(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return B(t,void 0)}}(n)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(),i=o[0],a=o.slice(1);if("number"==typeof i){I(t.bind(null,a),i);return}t(i),I(t.bind(null,a));return}"object"===L(n)&&e(n),"function"==typeof n&&n()}},{stop:function(){r=!0},start:function(t){r=!1,n(t)},subscribe:function(t){return e=t,function(){e=function(){return null}}}})}var o=t.begin,i=t.duration,a=t.attributeName,u=t.to,c=t.easing,l=t.onAnimationStart,s=t.onAnimationEnd,f=t.steps,p=t.children,h=this.manager;if(this.unSubscribe=h.subscribe(this.handleStyleChange),"function"==typeof c||"function"==typeof p||"spring"===c){this.runJSAnimation(t);return}if(f.length>1){this.runStepAnimation(t);return}var d=a?tm({},a,u):u,y=Z(Object.keys(d),i,c);h.start([l,o,tv(tv({},d),{},{transition:y}),i,s])}},{key:"render",value:function(){var t=this.props,e=t.children,r=(t.begin,t.duration),o=(t.attributeName,t.easing,t.isActive),i=(t.steps,t.from,t.to,t.canBegin,t.onAnimationEnd,t.shouldReAnimate,t.onAnimationReStart,function(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r,n,o={},i=Object.keys(t);for(n=0;n=0||(o[r]=t[r]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,tp)),a=n.Children.count(e),u=this.state.style;if("function"==typeof e)return e(u);if(!o||0===a||r<=0)return e;var c=function(t){var e=t.props,r=e.style,o=e.className;return(0,n.cloneElement)(t,tv(tv({},i),{},{style:tv(tv({},void 0===r?{}:r),u),className:o}))};return 1===a?c(n.Children.only(e)):n.createElement("div",null,n.Children.map(e,function(t){return c(t)}))}}],function(t,e){for(var r=0;r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,w),i=parseInt("".concat(r),10),a=parseInt("".concat(n),10),u=parseInt("".concat(e.height||o.height),10),c=parseInt("".concat(e.width||o.width),10);return P(P(P(P(P({},e),o),i?{x:i}:{}),a?{y:a}:{}),{},{height:u,width:c,name:e.name,radius:e.radius})}function k(t){return n.createElement(x.bn,j({shapeType:"rectangle",propTransformer:E,activeClassName:"recharts-active-bar"},t))}var A=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return function(r,n){if("number"==typeof t)return t;var o=(0,d.hj)(r)||(0,d.Rw)(r);return o?t(r,n):(o||(0,g.Z)(!1),e)}},M=["value","background"];function _(t){return(_="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function T(){return(T=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(e,M);if(!u)return null;var l=N(N(N(N(N({},c),{},{fill:"#eee"},u),a),(0,b.bw)(t.props,e,r)),{},{onAnimationStart:t.handleAnimationStart,onAnimationEnd:t.handleAnimationEnd,dataKey:o,index:r,className:"recharts-bar-background-rectangle"});return n.createElement(k,T({key:"background-bar-".concat(r),option:t.props.background,isActive:r===i},l))})}},{key:"renderErrorBar",value:function(t,e){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var r=this.props,o=r.data,i=r.xAxis,a=r.yAxis,u=r.layout,c=r.children,l=(0,y.NN)(c,f.W);if(!l)return null;var p="vertical"===u?o[0].height/2:o[0].width/2,h=function(t,e){var r=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:r,errorVal:(0,m.F$)(t,e)}};return n.createElement(s.m,{clipPath:t?"url(#clipPath-".concat(e,")"):null},l.map(function(t){return n.cloneElement(t,{key:"error-bar-".concat(e,"-").concat(t.props.dataKey),data:o,xAxis:i,yAxis:a,layout:u,offset:p,dataPointFormatter:h})}))}},{key:"render",value:function(){var t=this.props,e=t.hide,r=t.data,i=t.className,a=t.xAxis,u=t.yAxis,c=t.left,f=t.top,p=t.width,d=t.height,y=t.isAnimationActive,v=t.background,m=t.id;if(e||!r||!r.length)return null;var b=this.state.isAnimationFinished,g=(0,o.Z)("recharts-bar",i),x=a&&a.allowDataOverflow,w=u&&u.allowDataOverflow,O=x||w,j=l()(m)?this.id:m;return n.createElement(s.m,{className:g},x||w?n.createElement("defs",null,n.createElement("clipPath",{id:"clipPath-".concat(j)},n.createElement("rect",{x:x?c:c-p/2,y:w?f:f-d/2,width:x?p:2*p,height:w?d:2*d}))):null,n.createElement(s.m,{className:"recharts-bar-rectangles",clipPath:O?"url(#clipPath-".concat(j,")"):null},v?this.renderBackground():null,this.renderRectangles()),this.renderErrorBar(O,j),(!y||b)&&h.e.renderCallByParent(this.props,r))}}],r=[{key:"getDerivedStateFromProps",value:function(t,e){return t.animationId!==e.prevAnimationId?{prevAnimationId:t.animationId,curData:t.data,prevData:e.curData}:t.data!==e.curData?{curData:t.data}:null}}],e&&D(a.prototype,e),r&&D(a,r),Object.defineProperty(a,"prototype",{writable:!1}),a}(n.PureComponent);R(U,"displayName","Bar"),R(U,"defaultProps",{xAxisId:0,yAxisId:0,legendType:"rect",minPointSize:0,hide:!1,data:[],layout:"vertical",activeBar:!1,isAnimationActive:!v.x.isSsr,animationBegin:0,animationDuration:400,animationEasing:"ease"}),R(U,"getComposedData",function(t){var e=t.props,r=t.item,n=t.barPosition,o=t.bandSize,i=t.xAxis,a=t.yAxis,u=t.xAxisTicks,c=t.yAxisTicks,l=t.stackedData,s=t.dataStartIndex,f=t.displayedData,h=t.offset,v=(0,m.Bu)(n,r);if(!v)return null;var b=e.layout,g=r.type.defaultProps,x=void 0!==g?N(N({},g),r.props):r.props,w=x.dataKey,O=x.children,j=x.minPointSize,S="horizontal"===b?a:i,P=l?S.scale.domain():null,E=(0,m.Yj)({numericAxis:S}),k=(0,y.NN)(O,p.b),M=f.map(function(t,e){l?f=(0,m.Vv)(l[s+e],P):Array.isArray(f=(0,m.F$)(t,w))||(f=[E,f]);var n=A(j,U.defaultProps.minPointSize)(f[1],e);if("horizontal"===b){var f,p,h,y,g,x,O,S=[a.scale(f[0]),a.scale(f[1])],M=S[0],_=S[1];p=(0,m.Fy)({axis:i,ticks:u,bandSize:o,offset:v.offset,entry:t,index:e}),h=null!==(O=null!=_?_:M)&&void 0!==O?O:void 0,y=v.size;var T=M-_;if(g=Number.isNaN(T)?0:T,x={x:p,y:a.y,width:y,height:a.height},Math.abs(n)>0&&Math.abs(g)0&&Math.abs(y)=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function P(t,e){for(var r=0;r0?this.props:d)),o<=0||a<=0||!y||!y.length)?null:n.createElement(s.m,{className:(0,c.Z)("recharts-cartesian-axis",l),ref:function(e){t.layerReference=e}},r&&this.renderAxisLine(),this.renderTicks(y,this.state.fontSize,this.state.letterSpacing),p._.renderCallByParent(this.props))}}],r=[{key:"renderTickItem",value:function(t,e,r){var o=(0,c.Z)(e.className,"recharts-cartesian-axis-tick-value");return n.isValidElement(t)?n.cloneElement(t,j(j({},e),{},{className:o})):i()(t)?t(j(j({},e),{},{className:o})):n.createElement(f.x,w({},e,{className:"recharts-cartesian-axis-tick-value"}),r)}}],e&&P(o.prototype,e),r&&P(o,r),Object.defineProperty(o,"prototype",{writable:!1}),o}(n.Component);M(T,"displayName","CartesianAxis"),M(T,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"})},56940:function(t,e,r){"use strict";r.d(e,{q:function(){return M}});var n=r(2265),o=r(86757),i=r.n(o),a=r(1175),u=r(16630),c=r(82944),l=r(85355),s=r(78242),f=r(80285),p=r(25739),h=["x1","y1","x2","y2","key"],d=["offset"];function y(t){return(y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function v(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function m(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}var x=function(t){var e=t.fill;if(!e||"none"===e)return null;var r=t.fillOpacity,o=t.x,i=t.y,a=t.width,u=t.height,c=t.ry;return n.createElement("rect",{x:o,y:i,ry:c,width:a,height:u,stroke:"none",fill:e,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function w(t,e){var r;if(n.isValidElement(t))r=n.cloneElement(t,e);else if(i()(t))r=t(e);else{var o=e.x1,a=e.y1,u=e.x2,l=e.y2,s=e.key,f=g(e,h),p=(0,c.L6)(f,!1),y=(p.offset,g(p,d));r=n.createElement("line",b({},y,{x1:o,y1:a,x2:u,y2:l,fill:"none",key:s}))}return r}function O(t){var e=t.x,r=t.width,o=t.horizontal,i=void 0===o||o,a=t.horizontalPoints;if(!i||!a||!a.length)return null;var u=a.map(function(n,o){return w(i,m(m({},t),{},{x1:e,y1:n,x2:e+r,y2:n,key:"line-".concat(o),index:o}))});return n.createElement("g",{className:"recharts-cartesian-grid-horizontal"},u)}function j(t){var e=t.y,r=t.height,o=t.vertical,i=void 0===o||o,a=t.verticalPoints;if(!i||!a||!a.length)return null;var u=a.map(function(n,o){return w(i,m(m({},t),{},{x1:n,y1:e,x2:n,y2:e+r,key:"line-".concat(o),index:o}))});return n.createElement("g",{className:"recharts-cartesian-grid-vertical"},u)}function S(t){var e=t.horizontalFill,r=t.fillOpacity,o=t.x,i=t.y,a=t.width,u=t.height,c=t.horizontalPoints,l=t.horizontal;if(!(void 0===l||l)||!e||!e.length)return null;var s=c.map(function(t){return Math.round(t+i-i)}).sort(function(t,e){return t-e});i!==s[0]&&s.unshift(0);var f=s.map(function(t,c){var l=s[c+1]?s[c+1]-t:i+u-t;if(l<=0)return null;var f=c%e.length;return n.createElement("rect",{key:"react-".concat(c),y:t,x:o,height:l,width:a,stroke:"none",fill:e[f],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return n.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},f)}function P(t){var e=t.vertical,r=t.verticalFill,o=t.fillOpacity,i=t.x,a=t.y,u=t.width,c=t.height,l=t.verticalPoints;if(!(void 0===e||e)||!r||!r.length)return null;var s=l.map(function(t){return Math.round(t+i-i)}).sort(function(t,e){return t-e});i!==s[0]&&s.unshift(0);var f=s.map(function(t,e){var l=s[e+1]?s[e+1]-t:i+u-t;if(l<=0)return null;var f=e%r.length;return n.createElement("rect",{key:"react-".concat(e),x:t,y:a,width:l,height:c,stroke:"none",fill:r[f],fillOpacity:o,className:"recharts-cartesian-grid-bg"})});return n.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},f)}var E=function(t,e){var r=t.xAxis,n=t.width,o=t.height,i=t.offset;return(0,l.Rf)((0,s.f)(m(m(m({},f.O.defaultProps),r),{},{ticks:(0,l.uY)(r,!0),viewBox:{x:0,y:0,width:n,height:o}})),i.left,i.left+i.width,e)},k=function(t,e){var r=t.yAxis,n=t.width,o=t.height,i=t.offset;return(0,l.Rf)((0,s.f)(m(m(m({},f.O.defaultProps),r),{},{ticks:(0,l.uY)(r,!0),viewBox:{x:0,y:0,width:n,height:o}})),i.top,i.top+i.height,e)},A={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function M(t){var e,r,o,c,l,s,f=(0,p.zn)(),h=(0,p.Mw)(),d=(0,p.qD)(),v=m(m({},t),{},{stroke:null!==(e=t.stroke)&&void 0!==e?e:A.stroke,fill:null!==(r=t.fill)&&void 0!==r?r:A.fill,horizontal:null!==(o=t.horizontal)&&void 0!==o?o:A.horizontal,horizontalFill:null!==(c=t.horizontalFill)&&void 0!==c?c:A.horizontalFill,vertical:null!==(l=t.vertical)&&void 0!==l?l:A.vertical,verticalFill:null!==(s=t.verticalFill)&&void 0!==s?s:A.verticalFill,x:(0,u.hj)(t.x)?t.x:d.left,y:(0,u.hj)(t.y)?t.y:d.top,width:(0,u.hj)(t.width)?t.width:d.width,height:(0,u.hj)(t.height)?t.height:d.height}),g=v.x,w=v.y,M=v.width,_=v.height,T=v.syncWithTicks,C=v.horizontalValues,N=v.verticalValues,D=(0,p.CW)(),I=(0,p.Nf)();if(!(0,u.hj)(M)||M<=0||!(0,u.hj)(_)||_<=0||!(0,u.hj)(g)||g!==+g||!(0,u.hj)(w)||w!==+w)return null;var L=v.verticalCoordinatesGenerator||E,B=v.horizontalCoordinatesGenerator||k,R=v.horizontalPoints,z=v.verticalPoints;if((!R||!R.length)&&i()(B)){var U=C&&C.length,F=B({yAxis:I?m(m({},I),{},{ticks:U?C:I.ticks}):void 0,width:f,height:h,offset:d},!!U||T);(0,a.Z)(Array.isArray(F),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(y(F),"]")),Array.isArray(F)&&(R=F)}if((!z||!z.length)&&i()(L)){var $=N&&N.length,q=L({xAxis:D?m(m({},D),{},{ticks:$?N:D.ticks}):void 0,width:f,height:h,offset:d},!!$||T);(0,a.Z)(Array.isArray(q),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(y(q),"]")),Array.isArray(q)&&(z=q)}return n.createElement("g",{className:"recharts-cartesian-grid"},n.createElement(x,{fill:v.fill,fillOpacity:v.fillOpacity,x:v.x,y:v.y,width:v.width,height:v.height,ry:v.ry}),n.createElement(O,b({},v,{offset:d,horizontalPoints:R,xAxis:D,yAxis:I})),n.createElement(j,b({},v,{offset:d,verticalPoints:z,xAxis:D,yAxis:I})),n.createElement(S,b({},v,{horizontalPoints:R})),n.createElement(P,b({},v,{verticalPoints:z})))}M.displayName="CartesianGrid"},13137:function(t,e,r){"use strict";r.d(e,{W:function(){return v}});var n=r(2265),o=r(69398),i=r(9841),a=r(82944),u=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function c(t){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function l(){return(l=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,u),m=(0,a.L6)(v,!1);"x"===this.props.direction&&"number"!==d.type&&(0,o.Z)(!1);var b=p.map(function(t){var o,a,u=h(t,f),p=u.x,v=u.y,b=u.value,g=u.errorVal;if(!g)return null;var x=[];if(Array.isArray(g)){var w=function(t){if(Array.isArray(t))return t}(g)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{for(i=(r=r.call(t)).next;!(c=(n=i.call(r)).done)&&(u.push(n.value),2!==u.length);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(g,2)||function(t,e){if(t){if("string"==typeof t)return s(t,2);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return s(t,2)}}(g,2)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}();o=w[0],a=w[1]}else o=a=g;if("vertical"===r){var O=d.scale,j=v+e,S=j+c,P=j-c,E=O(b-o),k=O(b+a);x.push({x1:k,y1:S,x2:k,y2:P}),x.push({x1:E,y1:j,x2:k,y2:j}),x.push({x1:E,y1:S,x2:E,y2:P})}else if("horizontal"===r){var A=y.scale,M=p+e,_=M-c,T=M+c,C=A(b-o),N=A(b+a);x.push({x1:_,y1:N,x2:T,y2:N}),x.push({x1:M,y1:C,x2:M,y2:N}),x.push({x1:_,y1:C,x2:T,y2:C})}return n.createElement(i.m,l({className:"recharts-errorBar",key:"bar-".concat(x.map(function(t){return"".concat(t.x1,"-").concat(t.x2,"-").concat(t.y1,"-").concat(t.y2)}))},m),x.map(function(t){return n.createElement("line",l({},t,{key:"line-".concat(t.x1,"-").concat(t.x2,"-").concat(t.y1,"-").concat(t.y2)}))}))});return n.createElement(i.m,{className:"recharts-errorBars"},b)}}],function(t,e){for(var r=0;rt*o)return!1;var i=r();return t*(e-t*i/2-n)>=0&&t*(e+t*i/2-o)<=0}function f(t){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function p(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function h(t){for(var e=1;e=2?(0,i.uY)(m[1].coordinate-m[0].coordinate):1,M=(n="width"===P,f=b.x,p=b.y,d=b.width,y=b.height,1===A?{start:n?f:p,end:n?f+d:p+y}:{start:n?f+d:p+y,end:n?f:p});return"equidistantPreserveStart"===w?function(t,e,r,n,o){for(var i,a=(n||[]).slice(),u=e.start,c=e.end,f=0,p=1,h=u;p<=a.length;)if(i=function(){var e,i=null==n?void 0:n[f];if(void 0===i)return{v:l(n,p)};var a=f,d=function(){return void 0===e&&(e=r(i,a)),e},y=i.coordinate,v=0===f||s(t,y,d,h,c);v||(f=0,h=u,p+=1),v&&(h=y+t*(d()/2+o),f+=p)}())return i.v;return[]}(A,M,k,m,g):("preserveStart"===w||"preserveStartEnd"===w?function(t,e,r,n,o,i){var a=(n||[]).slice(),u=a.length,c=e.start,l=e.end;if(i){var f=n[u-1],p=r(f,u-1),d=t*(f.coordinate+t*p/2-l);a[u-1]=f=h(h({},f),{},{tickCoord:d>0?f.coordinate-d*t:f.coordinate}),s(t,f.tickCoord,function(){return p},c,l)&&(l=f.tickCoord-t*(p/2+o),a[u-1]=h(h({},f),{},{isShow:!0}))}for(var y=i?u-1:u,v=function(e){var n,i=a[e],u=function(){return void 0===n&&(n=r(i,e)),n};if(0===e){var f=t*(i.coordinate-t*u()/2-c);a[e]=i=h(h({},i),{},{tickCoord:f<0?i.coordinate-f*t:i.coordinate})}else a[e]=i=h(h({},i),{},{tickCoord:i.coordinate});s(t,i.tickCoord,u,c,l)&&(c=i.tickCoord+t*(u()/2+o),a[e]=h(h({},i),{},{isShow:!0}))},m=0;m0?l.coordinate-p*t:l.coordinate})}else i[e]=l=h(h({},l),{},{tickCoord:l.coordinate});s(t,l.tickCoord,f,u,c)&&(c=l.tickCoord-t*(f()/2+o),i[e]=h(h({},l),{},{isShow:!0}))},f=a-1;f>=0;f--)l(f);return i}(A,M,k,m,g)).filter(function(t){return t.isShow})}},93765:function(t,e,r){"use strict";r.d(e,{z:function(){return eD}});var n,o,i=r(2265),a=r(77571),u=r.n(a),c=r(86757),l=r.n(c),s=r(99676),f=r.n(s),p=r(13735),h=r.n(p),d=r(34935),y=r.n(d),v=r(37065),m=r.n(v),b=r(61994),g=r(69398),x=r(48777),w=r(9841),O=r(8147),j=r(22190),S=r(81889),P=r(73649),E=r(82944),k=r(55284),A=r(58811),M=r(85355),_=r(16630);function T(t){return(T="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function C(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function N(t){for(var e=1;e0&&e.handleDrag(t.changedTouches[0])}),W(e,"handleDragEnd",function(){e.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var t=e.props,r=t.endIndex,n=t.onDragEnd,o=t.startIndex;null==n||n({endIndex:r,startIndex:o})}),e.detachDragEndListener()}),W(e,"handleLeaveWrapper",function(){(e.state.isTravellerMoving||e.state.isSlideMoving)&&(e.leaveTimer=window.setTimeout(e.handleDragEnd,e.props.leaveTimeOut))}),W(e,"handleEnterSlideOrTraveller",function(){e.setState({isTextActive:!0})}),W(e,"handleLeaveSlideOrTraveller",function(){e.setState({isTextActive:!1})}),W(e,"handleSlideDragStart",function(t){var r=X(t)?t.changedTouches[0]:t;e.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:r.pageX}),e.attachDragEndListener()}),e.travellerDragStartHandlers={startX:e.handleTravellerDragStart.bind(e,"startX"),endX:e.handleTravellerDragStart.bind(e,"endX")},e.state={},e}return!function(t,e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Z(t,e)}(n,t),e=[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(t){var e=t.startX,r=t.endX,o=this.state.scaleValues,i=this.props,a=i.gap,u=i.data.length-1,c=n.getIndexInRange(o,Math.min(e,r)),l=n.getIndexInRange(o,Math.max(e,r));return{startIndex:c-c%a,endIndex:l===u?u:l-l%a}}},{key:"getTextOfTick",value:function(t){var e=this.props,r=e.data,n=e.tickFormatter,o=e.dataKey,i=(0,M.F$)(r[t],o,t);return l()(n)?n(i,t):i}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(t){var e=this.state,r=e.slideMoveStartX,n=e.startX,o=e.endX,i=this.props,a=i.x,u=i.width,c=i.travellerWidth,l=i.startIndex,s=i.endIndex,f=i.onChange,p=t.pageX-r;p>0?p=Math.min(p,a+u-c-o,a+u-c-n):p<0&&(p=Math.max(p,a-n,a-o));var h=this.getIndex({startX:n+p,endX:o+p});(h.startIndex!==l||h.endIndex!==s)&&f&&f(h),this.setState({startX:n+p,endX:o+p,slideMoveStartX:t.pageX})}},{key:"handleTravellerDragStart",value:function(t,e){var r=X(e)?e.changedTouches[0]:e;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:t,brushMoveStartX:r.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(t){var e=this.state,r=e.brushMoveStartX,n=e.movingTravellerId,o=e.endX,i=e.startX,a=this.state[n],u=this.props,c=u.x,l=u.width,s=u.travellerWidth,f=u.onChange,p=u.gap,h=u.data,d={startX:this.state.startX,endX:this.state.endX},y=t.pageX-r;y>0?y=Math.min(y,c+l-s-a):y<0&&(y=Math.max(y,c-a)),d[n]=a+y;var v=this.getIndex(d),m=v.startIndex,b=v.endIndex,g=function(){var t=h.length-1;return"startX"===n&&(o>i?m%p==0:b%p==0)||oi?b%p==0:m%p==0)||o>i&&b===t};this.setState(W(W({},n,a+y),"brushMoveStartX",t.pageX),function(){f&&g()&&f(v)})}},{key:"handleTravellerMoveKeyboard",value:function(t,e){var r=this,n=this.state,o=n.scaleValues,i=n.startX,a=n.endX,u=this.state[e],c=o.indexOf(u);if(-1!==c){var l=c+t;if(-1!==l&&!(l>=o.length)){var s=o[l];"startX"===e&&s>=a||"endX"===e&&s<=i||this.setState(W({},e,s),function(){r.props.onChange(r.getIndex({startX:r.state.startX,endX:r.state.endX}))})}}}},{key:"renderBackground",value:function(){var t=this.props,e=t.x,r=t.y,n=t.width,o=t.height,a=t.fill,u=t.stroke;return i.createElement("rect",{stroke:u,fill:a,x:e,y:r,width:n,height:o})}},{key:"renderPanorama",value:function(){var t=this.props,e=t.x,r=t.y,n=t.width,o=t.height,a=t.data,u=t.children,c=t.padding,l=i.Children.only(u);return l?i.cloneElement(l,{x:e,y:r,width:n,height:o,margin:c,compact:!0,data:a}):null}},{key:"renderTravellerLayer",value:function(t,e){var r,o,a=this,u=this.props,c=u.y,l=u.travellerWidth,s=u.height,f=u.traveller,p=u.ariaLabel,h=u.data,d=u.startIndex,y=u.endIndex,v=Math.max(t,this.props.x),m=U(U({},(0,E.L6)(this.props,!1)),{},{x:v,y:c,width:l,height:s}),b=p||"Min value: ".concat(null===(r=h[d])||void 0===r?void 0:r.name,", Max value: ").concat(null===(o=h[y])||void 0===o?void 0:o.name);return i.createElement(w.m,{tabIndex:0,role:"slider","aria-label":b,"aria-valuenow":t,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[e],onTouchStart:this.travellerDragStartHandlers[e],onKeyDown:function(t){["ArrowLeft","ArrowRight"].includes(t.key)&&(t.preventDefault(),t.stopPropagation(),a.handleTravellerMoveKeyboard("ArrowRight"===t.key?1:-1,e))},onFocus:function(){a.setState({isTravellerFocused:!0})},onBlur:function(){a.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},n.renderTraveller(f,m))}},{key:"renderSlide",value:function(t,e){var r=this.props,n=r.y,o=r.height,a=r.stroke,u=r.travellerWidth;return i.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:a,fillOpacity:.2,x:Math.min(t,e)+u,y:n,width:Math.max(Math.abs(e-t)-u,0),height:o})}},{key:"renderText",value:function(){var t=this.props,e=t.startIndex,r=t.endIndex,n=t.y,o=t.height,a=t.travellerWidth,u=t.stroke,c=this.state,l=c.startX,s=c.endX,f={pointerEvents:"none",fill:u};return i.createElement(w.m,{className:"recharts-brush-texts"},i.createElement(A.x,R({textAnchor:"end",verticalAnchor:"middle",x:Math.min(l,s)-5,y:n+o/2},f),this.getTextOfTick(e)),i.createElement(A.x,R({textAnchor:"start",verticalAnchor:"middle",x:Math.max(l,s)+a+5,y:n+o/2},f),this.getTextOfTick(r)))}},{key:"render",value:function(){var t=this.props,e=t.data,r=t.className,n=t.children,o=t.x,a=t.y,u=t.width,c=t.height,l=t.alwaysShowText,s=this.state,f=s.startX,p=s.endX,h=s.isTextActive,d=s.isSlideMoving,y=s.isTravellerMoving,v=s.isTravellerFocused;if(!e||!e.length||!(0,_.hj)(o)||!(0,_.hj)(a)||!(0,_.hj)(u)||!(0,_.hj)(c)||u<=0||c<=0)return null;var m=(0,b.Z)("recharts-brush",r),g=1===i.Children.count(n),x=L("userSelect","none");return i.createElement(w.m,{className:m,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:x},this.renderBackground(),g&&this.renderPanorama(),this.renderSlide(f,p),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(p,"endX"),(h||d||y||v||l)&&this.renderText())}}],r=[{key:"renderDefaultTraveller",value:function(t){var e=t.x,r=t.y,n=t.width,o=t.height,a=t.stroke,u=Math.floor(r+o/2)-1;return i.createElement(i.Fragment,null,i.createElement("rect",{x:e,y:r,width:n,height:o,fill:a,stroke:"none"}),i.createElement("line",{x1:e+1,y1:u,x2:e+n-1,y2:u,fill:"none",stroke:"#fff"}),i.createElement("line",{x1:e+1,y1:u+2,x2:e+n-1,y2:u+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(t,e){return i.isValidElement(t)?i.cloneElement(t,e):l()(t)?t(e):n.renderDefaultTraveller(e)}},{key:"getDerivedStateFromProps",value:function(t,e){var r=t.data,n=t.width,o=t.x,i=t.travellerWidth,a=t.updateId,u=t.startIndex,c=t.endIndex;if(r!==e.prevData||a!==e.prevUpdateId)return U({prevData:r,prevTravellerWidth:i,prevUpdateId:a,prevX:o,prevWidth:n},r&&r.length?H({data:r,width:n,x:o,travellerWidth:i,startIndex:u,endIndex:c}):{scale:null,scaleValues:null});if(e.scale&&(n!==e.prevWidth||o!==e.prevX||i!==e.prevTravellerWidth)){e.scale.range([o,o+n-i]);var l=e.scale.domain().map(function(t){return e.scale(t)});return{prevData:r,prevTravellerWidth:i,prevUpdateId:a,prevX:o,prevWidth:n,startX:e.scale(t.startIndex),endX:e.scale(t.endIndex),scaleValues:l}}return null}},{key:"getIndexInRange",value:function(t,e){for(var r=t.length,n=0,o=r-1;o-n>1;){var i=Math.floor((n+o)/2);t[i]>e?o=i:n=i}return e>=t[o]?o:n}}],e&&F(n.prototype,e),r&&F(n,r),Object.defineProperty(n,"prototype",{writable:!1}),n}(i.PureComponent);W(G,"displayName","Brush"),W(G,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var V=r(4094),K=r(38569),Q=r(26680),J=function(t,e){var r=t.alwaysShow,n=t.ifOverflow;return r&&(n="extendDomain"),n===e},tt=r(25311),te=r(1175);function tr(){return(tr=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);rt.length)&&(e=t.length);for(var r=0,n=Array(e);r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,t2));return(0,_.hj)(r)&&(0,_.hj)(o)&&(0,_.hj)(f)&&(0,_.hj)(h)&&(0,_.hj)(u)&&(0,_.hj)(l)?i.createElement("path",t5({},(0,E.L6)(y,!0),{className:(0,b.Z)("recharts-cross",d),d:"M".concat(r,",").concat(u,"v").concat(h,"M").concat(l,",").concat(o,"h").concat(f)})):null};function t7(t){var e=t.cx,r=t.cy,n=t.radius,o=t.startAngle,i=t.endAngle;return{points:[(0,tq.op)(e,r,n,o),(0,tq.op)(e,r,n,i)],cx:e,cy:r,radius:n,startAngle:o,endAngle:i}}var t4=r(60474);function t8(t){return(t8="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function t9(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function et(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function ec(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(ec=function(){return!!t})()}function el(t){return(el=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function es(t,e){return(es=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function ef(t){return function(t){if(Array.isArray(t))return eh(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||ep(t)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function ep(t,e){if(t){if("string"==typeof t)return eh(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return eh(t,e)}}function eh(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r0?i:t&&t.length&&(0,_.hj)(n)&&(0,_.hj)(o)?t.slice(n,o+1):[]};function eS(t){return"number"===t?[0,"auto"]:void 0}var eP=function(t,e,r,n){var o=t.graphicalItems,i=t.tooltipAxis,a=ej(e,t);return r<0||!o||!o.length||r>=a.length?null:o.reduce(function(o,u){var c,l,s=null!==(c=u.props.data)&&void 0!==c?c:e;if(s&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(s=s.slice(t.dataStartIndex,t.dataEndIndex+1)),i.dataKey&&!i.allowDuplicatedCategory){var f=void 0===s?a:s;l=(0,_.Ap)(f,i.dataKey,n)}else l=s&&s[r]||a[r];return l?[].concat(ef(o),[(0,M.Qo)(u,l)]):o},[])},eE=function(t,e,r,n){var o=n||{x:t.chartX,y:t.chartY},i="horizontal"===r?o.x:"vertical"===r?o.y:"centric"===r?o.angle:o.radius,a=t.orderedTooltipTicks,u=t.tooltipAxis,c=t.tooltipTicks,l=(0,M.VO)(i,a,c,u);if(l>=0&&c){var s=c[l]&&c[l].value,f=eP(t,e,l,s),p=eO(r,a,l,o);return{activeTooltipIndex:l,activeLabel:s,activePayload:f,activeCoordinate:p}}return null},ek=function(t,e){var r=e.axes,n=e.graphicalItems,o=e.axisType,i=e.axisIdKey,a=e.stackGroups,c=e.dataStartIndex,l=e.dataEndIndex,s=t.layout,p=t.children,h=t.stackOffset,d=(0,M.NA)(s,o);return r.reduce(function(e,r){var y=void 0!==r.type.defaultProps?ey(ey({},r.type.defaultProps),r.props):r.props,v=y.type,m=y.dataKey,b=y.allowDataOverflow,g=y.allowDuplicatedCategory,x=y.scale,w=y.ticks,O=y.includeHidden,j=y[i];if(e[j])return e;var S=ej(t.data,{graphicalItems:n.filter(function(t){var e;return(i in t.props?t.props[i]:null===(e=t.type.defaultProps)||void 0===e?void 0:e[i])===j}),dataStartIndex:c,dataEndIndex:l}),P=S.length;(function(t,e,r){if("number"===r&&!0===e&&Array.isArray(t)){var n=null==t?void 0:t[0],o=null==t?void 0:t[1];if(n&&o&&(0,_.hj)(n)&&(0,_.hj)(o))return!0}return!1})(y.domain,b,v)&&(A=(0,M.LG)(y.domain,null,b),d&&("number"===v||"auto"!==x)&&(C=(0,M.gF)(S,m,"category")));var E=eS(v);if(!A||0===A.length){var k,A,T,C,N,D=null!==(N=y.domain)&&void 0!==N?N:E;if(m){if(A=(0,M.gF)(S,m,v),"category"===v&&d){var I=(0,_.bv)(A);g&&I?(T=A,A=f()(0,P)):g||(A=(0,M.ko)(D,A,r).reduce(function(t,e){return t.indexOf(e)>=0?t:[].concat(ef(t),[e])},[]))}else if("category"===v)A=g?A.filter(function(t){return""!==t&&!u()(t)}):(0,M.ko)(D,A,r).reduce(function(t,e){return t.indexOf(e)>=0||""===e||u()(e)?t:[].concat(ef(t),[e])},[]);else if("number"===v){var L=(0,M.ZI)(S,n.filter(function(t){var e,r,n=i in t.props?t.props[i]:null===(e=t.type.defaultProps)||void 0===e?void 0:e[i],o="hide"in t.props?t.props.hide:null===(r=t.type.defaultProps)||void 0===r?void 0:r.hide;return n===j&&(O||!o)}),m,o,s);L&&(A=L)}d&&("number"===v||"auto"!==x)&&(C=(0,M.gF)(S,m,"category"))}else A=d?f()(0,P):a&&a[j]&&a[j].hasStack&&"number"===v?"expand"===h?[0,1]:(0,M.EB)(a[j].stackGroups,c,l):(0,M.s6)(S,n.filter(function(t){var e=i in t.props?t.props[i]:t.type.defaultProps[i],r="hide"in t.props?t.props.hide:t.type.defaultProps.hide;return e===j&&(O||!r)}),v,s,!0);"number"===v?(A=t$(p,A,j,o,w),D&&(A=(0,M.LG)(D,A,b))):"category"===v&&D&&A.every(function(t){return D.indexOf(t)>=0})&&(A=D)}return ey(ey({},e),{},ev({},j,ey(ey({},y),{},{axisType:o,domain:A,categoricalDomain:C,duplicateDomain:T,originalDomain:null!==(k=y.domain)&&void 0!==k?k:E,isCategorical:d,layout:s})))},{})},eA=function(t,e){var r=e.graphicalItems,n=e.Axis,o=e.axisType,i=e.axisIdKey,a=e.stackGroups,u=e.dataStartIndex,c=e.dataEndIndex,l=t.layout,s=t.children,p=ej(t.data,{graphicalItems:r,dataStartIndex:u,dataEndIndex:c}),d=p.length,y=(0,M.NA)(l,o),v=-1;return r.reduce(function(t,e){var m,b=(void 0!==e.type.defaultProps?ey(ey({},e.type.defaultProps),e.props):e.props)[i],g=eS("number");return t[b]?t:(v++,m=y?f()(0,d):a&&a[b]&&a[b].hasStack?t$(s,m=(0,M.EB)(a[b].stackGroups,u,c),b,o):t$(s,m=(0,M.LG)(g,(0,M.s6)(p,r.filter(function(t){var e,r,n=i in t.props?t.props[i]:null===(e=t.type.defaultProps)||void 0===e?void 0:e[i],o="hide"in t.props?t.props.hide:null===(r=t.type.defaultProps)||void 0===r?void 0:r.hide;return n===b&&!o}),"number",l),n.defaultProps.allowDataOverflow),b,o),ey(ey({},t),{},ev({},b,ey(ey({axisType:o},n.defaultProps),{},{hide:!0,orientation:h()(eb,"".concat(o,".").concat(v%2),null),domain:m,originalDomain:g,isCategorical:y,layout:l}))))},{})},eM=function(t,e){var r=e.axisType,n=void 0===r?"xAxis":r,o=e.AxisComp,i=e.graphicalItems,a=e.stackGroups,u=e.dataStartIndex,c=e.dataEndIndex,l=t.children,s="".concat(n,"Id"),f=(0,E.NN)(l,o),p={};return f&&f.length?p=ek(t,{axes:f,graphicalItems:i,axisType:n,axisIdKey:s,stackGroups:a,dataStartIndex:u,dataEndIndex:c}):i&&i.length&&(p=eA(t,{Axis:o,graphicalItems:i,axisType:n,axisIdKey:s,stackGroups:a,dataStartIndex:u,dataEndIndex:c})),p},e_=function(t){var e=(0,_.Kt)(t),r=(0,M.uY)(e,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:y()(r,function(t){return t.coordinate}),tooltipAxis:e,tooltipAxisBandSize:(0,M.zT)(e,r)}},eT=function(t){var e=t.children,r=t.defaultShowTooltip,n=(0,E.sP)(e,G),o=0,i=0;return t.data&&0!==t.data.length&&(i=t.data.length-1),n&&n.props&&(n.props.startIndex>=0&&(o=n.props.startIndex),n.props.endIndex>=0&&(i=n.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:o,dataEndIndex:i,activeTooltipIndex:-1,isTooltipActive:!!r}},eC=function(t){return"horizontal"===t?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:"vertical"===t?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:"centric"===t?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},eN=function(t,e){var r=t.props,n=t.graphicalItems,o=t.xAxisMap,i=void 0===o?{}:o,a=t.yAxisMap,u=void 0===a?{}:a,c=r.width,l=r.height,s=r.children,f=r.margin||{},p=(0,E.sP)(s,G),d=(0,E.sP)(s,j.D),y=Object.keys(u).reduce(function(t,e){var r=u[e],n=r.orientation;return r.mirror||r.hide?t:ey(ey({},t),{},ev({},n,t[n]+r.width))},{left:f.left||0,right:f.right||0}),v=Object.keys(i).reduce(function(t,e){var r=i[e],n=r.orientation;return r.mirror||r.hide?t:ey(ey({},t),{},ev({},n,h()(t,"".concat(n))+r.height))},{top:f.top||0,bottom:f.bottom||0}),m=ey(ey({},v),y),b=m.bottom;p&&(m.bottom+=p.props.height||G.defaultProps.height),d&&e&&(m=(0,M.By)(m,n,r,e));var g=c-m.left-m.right,x=l-m.top-m.bottom;return ey(ey({brushBottom:b},m),{},{width:Math.max(g,0),height:Math.max(x,0)})},eD=function(t){var e=t.chartName,r=t.GraphicalChild,n=t.defaultTooltipEventType,o=void 0===n?"axis":n,a=t.validateTooltipEventTypes,c=void 0===a?["axis"]:a,s=t.axisComponents,f=t.legendContent,p=t.formatAxisMap,d=t.defaultProps,y=function(t,e){var r=e.graphicalItems,n=e.stackGroups,o=e.offset,i=e.updateId,a=e.dataStartIndex,c=e.dataEndIndex,l=t.barSize,f=t.layout,p=t.barGap,h=t.barCategoryGap,d=t.maxBarSize,y=eC(f),v=y.numericAxisName,m=y.cateAxisName,b=!!r&&!!r.length&&r.some(function(t){var e=(0,E.Gf)(t&&t.type);return e&&e.indexOf("Bar")>=0}),x=[];return r.forEach(function(r,y){var w=ej(t.data,{graphicalItems:[r],dataStartIndex:a,dataEndIndex:c}),O=void 0!==r.type.defaultProps?ey(ey({},r.type.defaultProps),r.props):r.props,j=O.dataKey,S=O.maxBarSize,P=O["".concat(v,"Id")],k=O["".concat(m,"Id")],A=s.reduce(function(t,r){var n=e["".concat(r.axisType,"Map")],o=O["".concat(r.axisType,"Id")];n&&n[o]||"zAxis"===r.axisType||(0,g.Z)(!1);var i=n[o];return ey(ey({},t),{},ev(ev({},r.axisType,i),"".concat(r.axisType,"Ticks"),(0,M.uY)(i)))},{}),_=A[m],T=A["".concat(m,"Ticks")],C=n&&n[P]&&n[P].hasStack&&(0,M.O3)(r,n[P].stackGroups),N=(0,E.Gf)(r.type).indexOf("Bar")>=0,D=(0,M.zT)(_,T),I=[],L=b&&(0,M.pt)({barSize:l,stackGroups:n,totalSize:"xAxis"===m?A[m].width:"yAxis"===m?A[m].height:void 0});if(N){var B,R,z=u()(S)?d:S,U=null!==(B=null!==(R=(0,M.zT)(_,T,!0))&&void 0!==R?R:z)&&void 0!==B?B:0;I=(0,M.qz)({barGap:p,barCategoryGap:h,bandSize:U!==D?U:D,sizeList:L[k],maxBarSize:z}),U!==D&&(I=I.map(function(t){return ey(ey({},t),{},{position:ey(ey({},t.position),{},{offset:t.position.offset-U/2})})}))}var F=r&&r.type&&r.type.getComposedData;F&&x.push({props:ey(ey({},F(ey(ey({},A),{},{displayedData:w,props:t,dataKey:j,item:r,bandSize:D,barPosition:I,offset:o,stackedData:C,layout:f,dataStartIndex:a,dataEndIndex:c}))),{},ev(ev(ev({key:r.key||"item-".concat(y)},v,A[v]),m,A[m]),"animationId",i)),childIndex:(0,E.$R)(r,t.children),item:r})}),x},v=function(t,n){var o=t.props,i=t.dataStartIndex,a=t.dataEndIndex,u=t.updateId;if(!(0,E.TT)({props:o}))return null;var c=o.children,l=o.layout,f=o.stackOffset,h=o.data,d=o.reverseStackOrder,v=eC(l),m=v.numericAxisName,b=v.cateAxisName,g=(0,E.NN)(c,r),x=(0,M.wh)(h,g,"".concat(m,"Id"),"".concat(b,"Id"),f,d),w=s.reduce(function(t,e){var r="".concat(e.axisType,"Map");return ey(ey({},t),{},ev({},r,eM(o,ey(ey({},e),{},{graphicalItems:g,stackGroups:e.axisType===m&&x,dataStartIndex:i,dataEndIndex:a}))))},{}),O=eN(ey(ey({},w),{},{props:o,graphicalItems:g}),null==n?void 0:n.legendBBox);Object.keys(w).forEach(function(t){w[t]=p(o,w[t],O,t.replace("Map",""),e)});var j=e_(w["".concat(b,"Map")]),S=y(o,ey(ey({},w),{},{dataStartIndex:i,dataEndIndex:a,updateId:u,graphicalItems:g,stackGroups:x,offset:O}));return ey(ey({formattedGraphicalItems:S,graphicalItems:g,offset:O,stackGroups:x},j),w)},j=function(t){var r;function n(t){var r,o,a,c,s;return!function(t,e){if(!(t instanceof e))throw TypeError("Cannot call a class as a function")}(this,n),c=n,s=[t],c=el(c),ev(a=function(t,e){if(e&&("object"===eo(e)||"function"==typeof e))return e;if(void 0!==e)throw TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(this,ec()?Reflect.construct(c,s||[],el(this).constructor):c.apply(this,s)),"eventEmitterSymbol",Symbol("rechartsEventEmitter")),ev(a,"accessibilityManager",new tQ),ev(a,"handleLegendBBoxUpdate",function(t){if(t){var e=a.state,r=e.dataStartIndex,n=e.dataEndIndex,o=e.updateId;a.setState(ey({legendBBox:t},v({props:a.props,dataStartIndex:r,dataEndIndex:n,updateId:o},ey(ey({},a.state),{},{legendBBox:t}))))}}),ev(a,"handleReceiveSyncEvent",function(t,e,r){a.props.syncId===t&&(r!==a.eventEmitterSymbol||"function"==typeof a.props.syncMethod)&&a.applySyncEvent(e)}),ev(a,"handleBrushChange",function(t){var e=t.startIndex,r=t.endIndex;if(e!==a.state.dataStartIndex||r!==a.state.dataEndIndex){var n=a.state.updateId;a.setState(function(){return ey({dataStartIndex:e,dataEndIndex:r},v({props:a.props,dataStartIndex:e,dataEndIndex:r,updateId:n},a.state))}),a.triggerSyncEvent({dataStartIndex:e,dataEndIndex:r})}}),ev(a,"handleMouseEnter",function(t){var e=a.getMouseInfo(t);if(e){var r=ey(ey({},e),{},{isTooltipActive:!0});a.setState(r),a.triggerSyncEvent(r);var n=a.props.onMouseEnter;l()(n)&&n(r,t)}}),ev(a,"triggeredAfterMouseMove",function(t){var e=a.getMouseInfo(t),r=e?ey(ey({},e),{},{isTooltipActive:!0}):{isTooltipActive:!1};a.setState(r),a.triggerSyncEvent(r);var n=a.props.onMouseMove;l()(n)&&n(r,t)}),ev(a,"handleItemMouseEnter",function(t){a.setState(function(){return{isTooltipActive:!0,activeItem:t,activePayload:t.tooltipPayload,activeCoordinate:t.tooltipPosition||{x:t.cx,y:t.cy}}})}),ev(a,"handleItemMouseLeave",function(){a.setState(function(){return{isTooltipActive:!1}})}),ev(a,"handleMouseMove",function(t){t.persist(),a.throttleTriggeredAfterMouseMove(t)}),ev(a,"handleMouseLeave",function(t){a.throttleTriggeredAfterMouseMove.cancel();var e={isTooltipActive:!1};a.setState(e),a.triggerSyncEvent(e);var r=a.props.onMouseLeave;l()(r)&&r(e,t)}),ev(a,"handleOuterEvent",function(t){var e,r=(0,E.Bh)(t),n=h()(a.props,"".concat(r));r&&l()(n)&&n(null!==(e=/.*touch.*/i.test(r)?a.getMouseInfo(t.changedTouches[0]):a.getMouseInfo(t))&&void 0!==e?e:{},t)}),ev(a,"handleClick",function(t){var e=a.getMouseInfo(t);if(e){var r=ey(ey({},e),{},{isTooltipActive:!0});a.setState(r),a.triggerSyncEvent(r);var n=a.props.onClick;l()(n)&&n(r,t)}}),ev(a,"handleMouseDown",function(t){var e=a.props.onMouseDown;l()(e)&&e(a.getMouseInfo(t),t)}),ev(a,"handleMouseUp",function(t){var e=a.props.onMouseUp;l()(e)&&e(a.getMouseInfo(t),t)}),ev(a,"handleTouchMove",function(t){null!=t.changedTouches&&t.changedTouches.length>0&&a.throttleTriggeredAfterMouseMove(t.changedTouches[0])}),ev(a,"handleTouchStart",function(t){null!=t.changedTouches&&t.changedTouches.length>0&&a.handleMouseDown(t.changedTouches[0])}),ev(a,"handleTouchEnd",function(t){null!=t.changedTouches&&t.changedTouches.length>0&&a.handleMouseUp(t.changedTouches[0])}),ev(a,"handleDoubleClick",function(t){var e=a.props.onDoubleClick;l()(e)&&e(a.getMouseInfo(t),t)}),ev(a,"handleContextMenu",function(t){var e=a.props.onContextMenu;l()(e)&&e(a.getMouseInfo(t),t)}),ev(a,"triggerSyncEvent",function(t){void 0!==a.props.syncId&&tY.emit(tH,a.props.syncId,t,a.eventEmitterSymbol)}),ev(a,"applySyncEvent",function(t){var e=a.props,r=e.layout,n=e.syncMethod,o=a.state.updateId,i=t.dataStartIndex,u=t.dataEndIndex;if(void 0!==t.dataStartIndex||void 0!==t.dataEndIndex)a.setState(ey({dataStartIndex:i,dataEndIndex:u},v({props:a.props,dataStartIndex:i,dataEndIndex:u,updateId:o},a.state)));else if(void 0!==t.activeTooltipIndex){var c=t.chartX,l=t.chartY,s=t.activeTooltipIndex,f=a.state,p=f.offset,h=f.tooltipTicks;if(!p)return;if("function"==typeof n)s=n(h,t);else if("value"===n){s=-1;for(var d=0;d=0){if(s.dataKey&&!s.allowDuplicatedCategory){var A="function"==typeof s.dataKey?function(t){return"function"==typeof s.dataKey?s.dataKey(t.payload):null}:"payload.".concat(s.dataKey.toString());C=(0,_.Ap)(v,A,p),N=m&&b&&(0,_.Ap)(b,A,p)}else C=null==v?void 0:v[f],N=m&&b&&b[f];if(S||j){var T=void 0!==t.props.activeIndex?t.props.activeIndex:f;return[(0,i.cloneElement)(t,ey(ey(ey({},n.props),P),{},{activeIndex:T})),null,null]}if(!u()(C))return[k].concat(ef(a.renderActivePoints({item:n,activePoint:C,basePoint:N,childIndex:f,isRange:m})))}else{var C,N,D,I=(null!==(D=a.getItemByXY(a.state.activeCoordinate))&&void 0!==D?D:{graphicalItem:k}).graphicalItem,L=I.item,B=void 0===L?t:L,R=I.childIndex,z=ey(ey(ey({},n.props),P),{},{activeIndex:R});return[(0,i.cloneElement)(B,z),null,null]}}return m?[k,null,null]:[k,null]}),ev(a,"renderCustomized",function(t,e,r){return(0,i.cloneElement)(t,ey(ey({key:"recharts-customized-".concat(r)},a.props),a.state))}),ev(a,"renderMap",{CartesianGrid:{handler:ew,once:!0},ReferenceArea:{handler:a.renderReferenceElement},ReferenceLine:{handler:ew},ReferenceDot:{handler:a.renderReferenceElement},XAxis:{handler:ew},YAxis:{handler:ew},Brush:{handler:a.renderBrush,once:!0},Bar:{handler:a.renderGraphicChild},Line:{handler:a.renderGraphicChild},Area:{handler:a.renderGraphicChild},Radar:{handler:a.renderGraphicChild},RadialBar:{handler:a.renderGraphicChild},Scatter:{handler:a.renderGraphicChild},Pie:{handler:a.renderGraphicChild},Funnel:{handler:a.renderGraphicChild},Tooltip:{handler:a.renderCursor,once:!0},PolarGrid:{handler:a.renderPolarGrid,once:!0},PolarAngleAxis:{handler:a.renderPolarAxis},PolarRadiusAxis:{handler:a.renderPolarAxis},Customized:{handler:a.renderCustomized}}),a.clipPathId="".concat(null!==(r=t.id)&&void 0!==r?r:(0,_.EL)("recharts"),"-clip"),a.throttleTriggeredAfterMouseMove=m()(a.triggeredAfterMouseMove,null!==(o=t.throttleDelay)&&void 0!==o?o:1e3/60),a.state={},a}return!function(t,e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&es(t,e)}(n,t),r=[{key:"componentDidMount",value:function(){var t,e;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:null!==(t=this.props.margin.left)&&void 0!==t?t:0,top:null!==(e=this.props.margin.top)&&void 0!==e?e:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var t=this.props,e=t.children,r=t.data,n=t.height,o=t.layout,i=(0,E.sP)(e,O.u);if(i){var a=i.props.defaultIndex;if("number"==typeof a&&!(a<0)&&!(a>this.state.tooltipTicks.length-1)){var u=this.state.tooltipTicks[a]&&this.state.tooltipTicks[a].value,c=eP(this.state,r,a,u),l=this.state.tooltipTicks[a].coordinate,s=(this.state.offset.top+n)/2,f="horizontal"===o?{x:l,y:s}:{y:l,x:s},p=this.state.formattedGraphicalItems.find(function(t){return"Scatter"===t.item.type.name});p&&(f=ey(ey({},f),p.props.points[a].tooltipPosition),c=p.props.points[a].tooltipPayload);var h={activeTooltipIndex:a,isTooltipActive:!0,activeLabel:u,activePayload:c,activeCoordinate:f};this.setState(h),this.renderCursor(i),this.accessibilityManager.setIndex(a)}}}},{key:"getSnapshotBeforeUpdate",value:function(t,e){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==e.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==t.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==t.margin){var r,n;this.accessibilityManager.setDetails({offset:{left:null!==(r=this.props.margin.left)&&void 0!==r?r:0,top:null!==(n=this.props.margin.top)&&void 0!==n?n:0}})}return null}},{key:"componentDidUpdate",value:function(t){(0,E.rL)([(0,E.sP)(t.children,O.u)],[(0,E.sP)(this.props.children,O.u)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var t=(0,E.sP)(this.props.children,O.u);if(t&&"boolean"==typeof t.props.shared){var e=t.props.shared?"axis":"item";return c.indexOf(e)>=0?e:o}return o}},{key:"getMouseInfo",value:function(t){if(!this.container)return null;var e=this.container,r=e.getBoundingClientRect(),n=(0,V.os)(r),o={chartX:Math.round(t.pageX-n.left),chartY:Math.round(t.pageY-n.top)},i=r.width/e.offsetWidth||1,a=this.inRange(o.chartX,o.chartY,i);if(!a)return null;var u=this.state,c=u.xAxisMap,l=u.yAxisMap,s=this.getTooltipEventType(),f=eE(this.state,this.props.data,this.props.layout,a);if("axis"!==s&&c&&l){var p=(0,_.Kt)(c).scale,h=(0,_.Kt)(l).scale,d=p&&p.invert?p.invert(o.chartX):null,y=h&&h.invert?h.invert(o.chartY):null;return ey(ey({},o),{},{xValue:d,yValue:y},f)}return f?ey(ey({},o),f):null}},{key:"inRange",value:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=this.props.layout,o=t/r,i=e/r;if("horizontal"===n||"vertical"===n){var a=this.state.offset;return o>=a.left&&o<=a.left+a.width&&i>=a.top&&i<=a.top+a.height?{x:o,y:i}:null}var u=this.state,c=u.angleAxisMap,l=u.radiusAxisMap;if(c&&l){var s=(0,_.Kt)(c);return(0,tq.z3)({x:o,y:i},s)}return null}},{key:"parseEventsOfWrapper",value:function(){var t=this.props.children,e=this.getTooltipEventType(),r=(0,E.sP)(t,O.u),n={};return r&&"axis"===e&&(n="click"===r.props.trigger?{onClick:this.handleClick}:{onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu}),ey(ey({},(0,tX.Ym)(this.props,this.handleOuterEvent)),n)}},{key:"addListener",value:function(){tY.on(tH,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){tY.removeListener(tH,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(t,e,r){for(var n=this.state.formattedGraphicalItems,o=0,i=n.length;ot.length)&&(e=t.length);for(var r=0,n=Array(e);r=0?1:-1;"insideStart"===u?(o=b+S*l,a=w):"insideEnd"===u?(o=g-S*l,a=!w):"end"===u&&(o=g+S*l,a=w),a=j<=0?a:!a;var P=(0,d.op)(p,y,O,o),E=(0,d.op)(p,y,O,o+(a?1:-1)*359),k="M".concat(P.x,",").concat(P.y,"\n A").concat(O,",").concat(O,",0,1,").concat(a?0:1,",\n ").concat(E.x,",").concat(E.y),A=i()(t.id)?(0,h.EL)("recharts-radial-line-"):t.id;return n.createElement("text",x({},r,{dominantBaseline:"central",className:(0,s.Z)("recharts-radial-bar-label",f)}),n.createElement("defs",null,n.createElement("path",{id:A,d:k})),n.createElement("textPath",{xlinkHref:"#".concat(A)},e))},j=function(t){var e=t.viewBox,r=t.offset,n=t.position,o=e.cx,i=e.cy,a=e.innerRadius,u=e.outerRadius,c=(e.startAngle+e.endAngle)/2;if("outside"===n){var l=(0,d.op)(o,i,u+r,c),s=l.x;return{x:s,y:l.y,textAnchor:s>=o?"start":"end",verticalAnchor:"middle"}}if("center"===n)return{x:o,y:i,textAnchor:"middle",verticalAnchor:"middle"};if("centerTop"===n)return{x:o,y:i,textAnchor:"middle",verticalAnchor:"start"};if("centerBottom"===n)return{x:o,y:i,textAnchor:"middle",verticalAnchor:"end"};var f=(0,d.op)(o,i,(a+u)/2,c);return{x:f.x,y:f.y,textAnchor:"middle",verticalAnchor:"middle"}},S=function(t){var e=t.viewBox,r=t.parentViewBox,n=t.offset,o=t.position,i=e.x,a=e.y,u=e.width,c=e.height,s=c>=0?1:-1,f=s*n,p=s>0?"end":"start",d=s>0?"start":"end",y=u>=0?1:-1,v=y*n,m=y>0?"end":"start",b=y>0?"start":"end";if("top"===o)return g(g({},{x:i+u/2,y:a-s*n,textAnchor:"middle",verticalAnchor:p}),r?{height:Math.max(a-r.y,0),width:u}:{});if("bottom"===o)return g(g({},{x:i+u/2,y:a+c+f,textAnchor:"middle",verticalAnchor:d}),r?{height:Math.max(r.y+r.height-(a+c),0),width:u}:{});if("left"===o){var x={x:i-v,y:a+c/2,textAnchor:m,verticalAnchor:"middle"};return g(g({},x),r?{width:Math.max(x.x-r.x,0),height:c}:{})}if("right"===o){var w={x:i+u+v,y:a+c/2,textAnchor:b,verticalAnchor:"middle"};return g(g({},w),r?{width:Math.max(r.x+r.width-w.x,0),height:c}:{})}var O=r?{width:u,height:c}:{};return"insideLeft"===o?g({x:i+v,y:a+c/2,textAnchor:b,verticalAnchor:"middle"},O):"insideRight"===o?g({x:i+u-v,y:a+c/2,textAnchor:m,verticalAnchor:"middle"},O):"insideTop"===o?g({x:i+u/2,y:a+f,textAnchor:"middle",verticalAnchor:d},O):"insideBottom"===o?g({x:i+u/2,y:a+c-f,textAnchor:"middle",verticalAnchor:p},O):"insideTopLeft"===o?g({x:i+v,y:a+f,textAnchor:b,verticalAnchor:d},O):"insideTopRight"===o?g({x:i+u-v,y:a+f,textAnchor:m,verticalAnchor:d},O):"insideBottomLeft"===o?g({x:i+v,y:a+c-f,textAnchor:b,verticalAnchor:p},O):"insideBottomRight"===o?g({x:i+u-v,y:a+c-f,textAnchor:m,verticalAnchor:p},O):l()(o)&&((0,h.hj)(o.x)||(0,h.hU)(o.x))&&((0,h.hj)(o.y)||(0,h.hU)(o.y))?g({x:i+(0,h.h1)(o.x,u),y:a+(0,h.h1)(o.y,c),textAnchor:"end",verticalAnchor:"end"},O):g({x:i+u/2,y:a+c/2,textAnchor:"middle",verticalAnchor:"middle"},O)};function P(t){var e,r=t.offset,o=g({offset:void 0===r?5:r},function(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,v)),a=o.viewBox,c=o.position,l=o.value,d=o.children,y=o.content,m=o.className,b=o.textBreakAll;if(!a||i()(l)&&i()(d)&&!(0,n.isValidElement)(y)&&!u()(y))return null;if((0,n.isValidElement)(y))return(0,n.cloneElement)(y,o);if(u()(y)){if(e=(0,n.createElement)(y,o),(0,n.isValidElement)(e))return e}else e=w(o);var P="cx"in a&&(0,h.hj)(a.cx),E=(0,p.L6)(o,!0);if(P&&("insideStart"===c||"insideEnd"===c||"end"===c))return O(o,e,E);var k=P?j(o):S(o);return n.createElement(f.x,x({className:(0,s.Z)("recharts-label",void 0===m?"":m)},E,k,{breakAll:b}),e)}P.displayName="Label";var E=function(t){var e=t.cx,r=t.cy,n=t.angle,o=t.startAngle,i=t.endAngle,a=t.r,u=t.radius,c=t.innerRadius,l=t.outerRadius,s=t.x,f=t.y,p=t.top,d=t.left,y=t.width,v=t.height,m=t.clockWise,b=t.labelViewBox;if(b)return b;if((0,h.hj)(y)&&(0,h.hj)(v)){if((0,h.hj)(s)&&(0,h.hj)(f))return{x:s,y:f,width:y,height:v};if((0,h.hj)(p)&&(0,h.hj)(d))return{x:p,y:d,width:y,height:v}}return(0,h.hj)(s)&&(0,h.hj)(f)?{x:s,y:f,width:0,height:0}:(0,h.hj)(e)&&(0,h.hj)(r)?{cx:e,cy:r,startAngle:o||n||0,endAngle:i||n||0,innerRadius:c||0,outerRadius:l||u||a||0,clockWise:m}:t.viewBox?t.viewBox:{}};P.parseViewBox=E,P.renderCallByParent=function(t,e){var r,o,i=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(!t||!t.children&&i&&!t.label)return null;var a=t.children,c=E(t),s=(0,p.NN)(a,P).map(function(t,r){return(0,n.cloneElement)(t,{viewBox:e||c,key:"label-".concat(r)})});return i?[(r=t.label,o=e||c,r?!0===r?n.createElement(P,{key:"label-implicit",viewBox:o}):(0,h.P2)(r)?n.createElement(P,{key:"label-implicit",viewBox:o,value:r}):(0,n.isValidElement)(r)?r.type===P?(0,n.cloneElement)(r,{key:"label-implicit",viewBox:o}):n.createElement(P,{key:"label-implicit",content:r,viewBox:o}):u()(r)?n.createElement(P,{key:"label-implicit",content:r,viewBox:o}):l()(r)?n.createElement(P,x({viewBox:o},r,{key:"label-implicit"})):null:null)].concat(function(t){if(Array.isArray(t))return m(t)}(s)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(s)||function(t,e){if(t){if("string"==typeof t)return m(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return m(t,void 0)}}(s)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()):s}},58772:function(t,e,r){"use strict";r.d(e,{e:function(){return P}});var n=r(2265),o=r(77571),i=r.n(o),a=r(28302),u=r.n(a),c=r(86757),l=r.n(c),s=r(86185),f=r.n(s),p=r(26680),h=r(9841),d=r(82944),y=r(85355);function v(t){return(v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var m=["valueAccessor"],b=["data","dataKey","clockWise","id","textBreakAll"];function g(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}var S=function(t){return Array.isArray(t.value)?f()(t.value):t.value};function P(t){var e=t.valueAccessor,r=void 0===e?S:e,o=j(t,m),a=o.data,u=o.dataKey,c=o.clockWise,l=o.id,s=o.textBreakAll,f=j(o,b);return a&&a.length?n.createElement(h.m,{className:"recharts-label-list"},a.map(function(t,e){var o=i()(u)?r(t,e):(0,y.F$)(t&&t.payload,u),a=i()(l)?{}:{id:"".concat(l,"-").concat(e)};return n.createElement(p._,x({},(0,d.L6)(t,!0),f,a,{parentViewBox:t.parentViewBox,value:o,textBreakAll:s,viewBox:p._.parseViewBox(i()(c)?t:O(O({},t),{},{clockWise:c})),key:"label-".concat(e),index:e}))})):null}P.displayName="LabelList",P.renderCallByParent=function(t,e){var r,o=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(!t||!t.children&&o&&!t.label)return null;var i=t.children,a=(0,d.NN)(i,P).map(function(t,r){return(0,n.cloneElement)(t,{data:e,key:"labelList-".concat(r)})});return o?[(r=t.label)?!0===r?n.createElement(P,{key:"labelList-implicit",data:e}):n.isValidElement(r)||l()(r)?n.createElement(P,{key:"labelList-implicit",data:e,content:r}):u()(r)?n.createElement(P,x({data:e},r,{key:"labelList-implicit"})):null:null].concat(function(t){if(Array.isArray(t))return g(t)}(a)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(a)||function(t,e){if(t){if("string"==typeof t)return g(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return g(t,void 0)}}(a)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()):a}},22190:function(t,e,r){"use strict";r.d(e,{D:function(){return N}});var n=r(2265),o=r(86757),i=r.n(o),a=r(61994),u=r(1175),c=r(48777),l=r(14870),s=r(41637);function f(t){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function p(){return(p=Object.assign?Object.assign.bind():function(t){for(var e=1;e');var x=e.inactive?h:e.color;return n.createElement("li",p({className:b,style:y,key:"legend-item-".concat(r)},(0,s.bw)(t.props,e,r)),n.createElement(c.T,{width:o,height:o,viewBox:d,style:v},t.renderIcon(e)),n.createElement("span",{className:"recharts-legend-item-text",style:{color:x}},l?l(g,e,r):g))})}},{key:"render",value:function(){var t=this.props,e=t.payload,r=t.layout,o=t.align;return e&&e.length?n.createElement("ul",{className:"recharts-default-legend",style:{padding:0,margin:0,textAlign:"horizontal"===r?o:"left"}},this.renderItems()):null}}],function(t,e){for(var r=0;r1||Math.abs(e.height-this.lastBoundingBox.height)>1)&&(this.lastBoundingBox.width=e.width,this.lastBoundingBox.height=e.height,t&&t(e)):(-1!==this.lastBoundingBox.width||-1!==this.lastBoundingBox.height)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,t&&t(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?P({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(t){var e,r,n=this.props,o=n.layout,i=n.align,a=n.verticalAlign,u=n.margin,c=n.chartWidth,l=n.chartHeight;return t&&(void 0!==t.left&&null!==t.left||void 0!==t.right&&null!==t.right)||(e="center"===i&&"vertical"===o?{left:((c||0)-this.getBBoxSnapshot().width)/2}:"right"===i?{right:u&&u.right||0}:{left:u&&u.left||0}),t&&(void 0!==t.top&&null!==t.top||void 0!==t.bottom&&null!==t.bottom)||(r="middle"===a?{top:((l||0)-this.getBBoxSnapshot().height)/2}:"bottom"===a?{bottom:u&&u.bottom||0}:{top:u&&u.top||0}),P(P({},e),r)}},{key:"render",value:function(){var t=this,e=this.props,r=e.content,o=e.width,i=e.height,a=e.wrapperStyle,u=e.payloadUniqBy,c=e.payload,l=P(P({position:"absolute",width:o||"auto",height:i||"auto"},this.getDefaultPosition(a)),a);return n.createElement("div",{className:"recharts-legend-wrapper",style:l,ref:function(e){t.wrapperNode=e}},function(t,e){if(n.isValidElement(t))return n.cloneElement(t,e);if("function"==typeof t)return n.createElement(t,e);e.ref;var r=function(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(e,j);return n.createElement(g,r)}(r,P(P({},this.props),{},{payload:(0,w.z)(c,u,C)})))}}],r=[{key:"getWithHeight",value:function(t,e){var r=P(P({},this.defaultProps),t.props).layout;return"vertical"===r&&(0,x.hj)(t.props.height)?{height:t.props.height}:"horizontal"===r?{width:t.props.width||e}:null}}],e&&E(o.prototype,e),r&&E(o,r),Object.defineProperty(o,"prototype",{writable:!1}),o}(n.PureComponent);_(N,"displayName","Legend"),_(N,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"})},47625:function(t,e,r){"use strict";r.d(e,{h:function(){return d}});var n=r(61994),o=r(2265),i=r(37065),a=r.n(i),u=r(16630),c=r(1175),l=r(82944);function s(t){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function f(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function p(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);r0&&(t=a()(t,S,{trailing:!0,leading:!1}));var e=new ResizeObserver(t),r=M.current.getBoundingClientRect();return D(r.width,r.height),e.observe(M.current),function(){e.disconnect()}},[D,S]);var I=(0,o.useMemo)(function(){var t=C.containerWidth,e=C.containerHeight;if(t<0||e<0)return null;(0,c.Z)((0,u.hU)(y)||(0,u.hU)(m),"The width(%s) and height(%s) are both fixed numbers,\n maybe you don't need to use a ResponsiveContainer.",y,m),(0,c.Z)(!i||i>0,"The aspect(%s) must be greater than zero.",i);var r=(0,u.hU)(y)?t:y,n=(0,u.hU)(m)?e:m;i&&i>0&&(r?n=r/i:n&&(r=n*i),w&&n>w&&(n=w)),(0,c.Z)(r>0||n>0,"The width(%s) and height(%s) of chart should be greater than 0,\n please check the style of container, or the props width(%s) and height(%s),\n or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the\n height and width.",r,n,y,m,g,x,i);var a=!Array.isArray(O)&&(0,l.Gf)(O.type).endsWith("Chart");return o.Children.map(O,function(t){return o.isValidElement(t)?(0,o.cloneElement)(t,p({width:r,height:n},a?{style:p({height:"100%",width:"100%",maxHeight:n,maxWidth:r},t.props.style)}:{})):t})},[i,O,m,w,x,g,C,y]);return o.createElement("div",{id:P?"".concat(P):void 0,className:(0,n.Z)("recharts-responsive-container",E),style:p(p({},void 0===A?{}:A),{},{width:y,height:m,minWidth:g,minHeight:x,maxHeight:w}),ref:M},I)})},58811:function(t,e,r){"use strict";r.d(e,{x:function(){return B}});var n=r(2265),o=r(77571),i=r.n(o),a=r(61994),u=r(16630),c=r(34067),l=r(82944),s=r(4094);function f(t){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function p(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(u.push(n.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return h(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return h(t,e)}}(t,e)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function M(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(u.push(n.value),u.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(t,e)||function(t,e){if(t){if("string"==typeof t)return _(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return _(t,e)}}(t,e)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r0&&void 0!==arguments[0]?arguments[0]:[];return t.reduce(function(t,e){var i=e.word,a=e.width,u=t[t.length-1];return u&&(null==n||o||u.width+a+ra||e.reduce(function(t,e){return t.width>e.width?t:e}).width>Number(n),e]},y=0,v=c.length-1,m=0;y<=v&&m<=c.length-1;){var b=Math.floor((y+v)/2),g=M(d(b-1),2),x=g[0],w=g[1],O=M(d(b),1)[0];if(x||O||(y=b+1),x&&O&&(v=b-1),!x&&O){i=w;break}m++}return i||h},D=function(t){return[{words:i()(t)?[]:t.toString().split(T)}]},I=function(t){var e=t.width,r=t.scaleToFit,n=t.children,o=t.style,i=t.breakAll,a=t.maxLines;if((e||r)&&!c.x.isSsr){var u=C({breakAll:i,children:n,style:o});return u?N({breakAll:i,children:n,maxLines:a,style:o},u.wordsWithComputedWidth,u.spaceWidth,e,r):D(n)}return D(n)},L="#808080",B=function(t){var e,r=t.x,o=void 0===r?0:r,i=t.y,c=void 0===i?0:i,s=t.lineHeight,f=void 0===s?"1em":s,p=t.capHeight,h=void 0===p?"0.71em":p,d=t.scaleToFit,y=void 0!==d&&d,v=t.textAnchor,m=t.verticalAnchor,b=t.fill,g=void 0===b?L:b,x=A(t,P),w=(0,n.useMemo)(function(){return I({breakAll:x.breakAll,children:x.children,maxLines:x.maxLines,scaleToFit:y,style:x.style,width:x.width})},[x.breakAll,x.children,x.maxLines,y,x.style,x.width]),O=x.dx,j=x.dy,M=x.angle,_=x.className,T=x.breakAll,C=A(x,E);if(!(0,u.P2)(o)||!(0,u.P2)(c))return null;var N=o+((0,u.hj)(O)?O:0),D=c+((0,u.hj)(j)?j:0);switch(void 0===m?"end":m){case"start":e=S("calc(".concat(h,")"));break;case"middle":e=S("calc(".concat((w.length-1)/2," * -").concat(f," + (").concat(h," / 2))"));break;default:e=S("calc(".concat(w.length-1," * -").concat(f,")"))}var B=[];if(y){var R=w[0].width,z=x.width;B.push("scale(".concat(((0,u.hj)(z)?z/R:1)/R,")"))}return M&&B.push("rotate(".concat(M,", ").concat(N,", ").concat(D,")")),B.length&&(C.transform=B.join(" ")),n.createElement("text",k({},(0,l.L6)(C,!0),{x:N,y:D,className:(0,a.Z)("recharts-text",_),textAnchor:void 0===v?"start":v,fill:g.includes("url")?L:g}),w.map(function(t,r){var o=t.words.join(T?"":" ");return n.createElement("tspan",{x:N,dy:0===r?e:f,key:"".concat(o,"-").concat(r)},o)}))}},8147:function(t,e,r){"use strict";r.d(e,{u:function(){return $}});var n=r(2265),o=r(34935),i=r.n(o),a=r(77571),u=r.n(a),c=r(61994),l=r(16630);function s(t){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function f(){return(f=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);rc[n]+s?Math.max(f,c[n]):Math.max(p,c[n])}function O(t){return(O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function j(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function S(t){for(var e=1;e1||Math.abs(t.height-this.state.lastBoundingBox.height)>1)&&this.setState({lastBoundingBox:{width:t.width,height:t.height}})}else(-1!==this.state.lastBoundingBox.width||-1!==this.state.lastBoundingBox.height)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var t,e;this.props.active&&this.updateBBox(),this.state.dismissed&&((null===(t=this.props.coordinate)||void 0===t?void 0:t.x)!==this.state.dismissedAtCoordinate.x||(null===(e=this.props.coordinate)||void 0===e?void 0:e.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var t,e,r,o,i,a,u,s,f,p,h,d,y,v,m,O,j,P,E,k=this,A=this.props,M=A.active,_=A.allowEscapeViewBox,T=A.animationDuration,C=A.animationEasing,N=A.children,D=A.coordinate,I=A.hasPayload,L=A.isAnimationActive,B=A.offset,R=A.position,z=A.reverseDirection,U=A.useTranslate3d,F=A.viewBox,$=A.wrapperStyle,q=(d=(t={allowEscapeViewBox:_,coordinate:D,offsetTopLeft:B,position:R,reverseDirection:z,tooltipBox:this.state.lastBoundingBox,useTranslate3d:U,viewBox:F}).allowEscapeViewBox,y=t.coordinate,v=t.offsetTopLeft,m=t.position,O=t.reverseDirection,j=t.tooltipBox,P=t.useTranslate3d,E=t.viewBox,j.height>0&&j.width>0&&y?(r=(e={translateX:p=w({allowEscapeViewBox:d,coordinate:y,key:"x",offsetTopLeft:v,position:m,reverseDirection:O,tooltipDimension:j.width,viewBox:E,viewBoxDimension:E.width}),translateY:h=w({allowEscapeViewBox:d,coordinate:y,key:"y",offsetTopLeft:v,position:m,reverseDirection:O,tooltipDimension:j.height,viewBox:E,viewBoxDimension:E.height}),useTranslate3d:P}).translateX,o=e.translateY,f={transform:e.useTranslate3d?"translate3d(".concat(r,"px, ").concat(o,"px, 0)"):"translate(".concat(r,"px, ").concat(o,"px)")}):f=x,{cssProperties:f,cssClasses:(a=(i={translateX:p,translateY:h,coordinate:y}).coordinate,u=i.translateX,s=i.translateY,(0,c.Z)(g,b(b(b(b({},"".concat(g,"-right"),(0,l.hj)(u)&&a&&(0,l.hj)(a.x)&&u>=a.x),"".concat(g,"-left"),(0,l.hj)(u)&&a&&(0,l.hj)(a.x)&&u=a.y),"".concat(g,"-top"),(0,l.hj)(s)&&a&&(0,l.hj)(a.y)&&s0;return n.createElement(_,{allowEscapeViewBox:i,animationDuration:a,animationEasing:u,isAnimationActive:f,active:o,coordinate:l,hasPayload:O,offset:p,position:y,reverseDirection:m,useTranslate3d:b,viewBox:g,wrapperStyle:x},(t=I(I({},this.props),{},{payload:w}),n.isValidElement(c)?n.cloneElement(c,t):"function"==typeof c?n.createElement(c,t):n.createElement(v,t)))}}],function(t,e){for(var r=0;r=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,a),s=(0,o.Z)("recharts-layer",c);return n.createElement("g",u({className:s},(0,i.L6)(l,!0),{ref:e}),r)})},48777:function(t,e,r){"use strict";r.d(e,{T:function(){return c}});var n=r(2265),o=r(61994),i=r(82944),a=["children","width","height","viewBox","className","style","title","desc"];function u(){return(u=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,a),y=l||{width:r,height:c,x:0,y:0},v=(0,o.Z)("recharts-surface",s);return n.createElement("svg",u({},(0,i.L6)(d,!0,"svg"),{className:v,width:r,height:c,style:f,viewBox:"".concat(y.x," ").concat(y.y," ").concat(y.width," ").concat(y.height)}),n.createElement("title",null,p),n.createElement("desc",null,h),e)}},25739:function(t,e,r){"use strict";r.d(e,{br:function(){return g},CW:function(){return O},Mw:function(){return A},zn:function(){return k},sp:function(){return x},qD:function(){return E},d2:function(){return P},bH:function(){return w},Ud:function(){return S},Nf:function(){return j}});var n=r(2265),o=r(69398),i=r(84173),a=r.n(i),u=r(32242),c=r.n(u),l=r(50967),s=r.n(l)()(function(t){return{x:t.left,y:t.top,width:t.width,height:t.height}},function(t){return["l",t.left,"t",t.top,"w",t.width,"h",t.height].join("")}),f=r(16630),p=(0,n.createContext)(void 0),h=(0,n.createContext)(void 0),d=(0,n.createContext)(void 0),y=(0,n.createContext)({}),v=(0,n.createContext)(void 0),m=(0,n.createContext)(0),b=(0,n.createContext)(0),g=function(t){var e=t.state,r=e.xAxisMap,o=e.yAxisMap,i=e.offset,a=t.clipPathId,u=t.children,c=t.width,l=t.height,f=s(i);return n.createElement(p.Provider,{value:r},n.createElement(h.Provider,{value:o},n.createElement(y.Provider,{value:i},n.createElement(d.Provider,{value:f},n.createElement(v.Provider,{value:a},n.createElement(m.Provider,{value:l},n.createElement(b.Provider,{value:c},u)))))))},x=function(){return(0,n.useContext)(v)},w=function(t){var e=(0,n.useContext)(p);null!=e||(0,o.Z)(!1);var r=e[t];return null!=r||(0,o.Z)(!1),r},O=function(){var t=(0,n.useContext)(p);return(0,f.Kt)(t)},j=function(){var t=(0,n.useContext)(h);return a()(t,function(t){return c()(t.domain,Number.isFinite)})||(0,f.Kt)(t)},S=function(t){var e=(0,n.useContext)(h);null!=e||(0,o.Z)(!1);var r=e[t];return null!=r||(0,o.Z)(!1),r},P=function(){return(0,n.useContext)(d)},E=function(){return(0,n.useContext)(y)},k=function(){return(0,n.useContext)(b)},A=function(){return(0,n.useContext)(m)}},57165:function(t,e,r){"use strict";r.d(e,{H:function(){return H}});var n=r(2265);function o(){}function i(t,e,r){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+r)/6)}function a(t){this._context=t}function u(t){this._context=t}function c(t){this._context=t}a.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:i(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:i(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},u.prototype={areaStart:o,areaEnd:o,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:i(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},c.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+t)/6,n=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:i(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};class l{constructor(t,e){this._context=t,this._x=e}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,e,t,e):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+e)/2,t,this._y0,t,e)}this._x0=t,this._y0=e}}function s(t){this._context=t}function f(t){this._context=t}function p(t){return new f(t)}function h(t,e,r){var n=t._x1-t._x0,o=e-t._x1,i=(t._y1-t._y0)/(n||o<0&&-0),a=(r-t._y1)/(o||n<0&&-0);return((i<0?-1:1)+(a<0?-1:1))*Math.min(Math.abs(i),Math.abs(a),.5*Math.abs((i*o+a*n)/(n+o)))||0}function d(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function y(t,e,r){var n=t._x0,o=t._y0,i=t._x1,a=t._y1,u=(i-n)/3;t._context.bezierCurveTo(n+u,o+u*e,i-u,a-u*r,i,a)}function v(t){this._context=t}function m(t){this._context=new b(t)}function b(t){this._context=t}function g(t){this._context=t}function x(t){var e,r,n=t.length-1,o=Array(n),i=Array(n),a=Array(n);for(o[0]=0,i[0]=2,a[0]=t[0]+2*t[1],e=1;e=0;--e)o[e]=(a[e]-o[e+1])/i[e];for(e=0,i[n-1]=(t[n]+o[n-1])/2;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var r=this._x*(1-this._t)+t*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,e)}}this._x=t,this._y=e}};var O=r(22516),j=r(76115),S=r(67790);function P(t){return t[0]}function E(t){return t[1]}function k(t,e){var r=(0,j.Z)(!0),n=null,o=p,i=null,a=(0,S.d)(u);function u(u){var c,l,s,f=(u=(0,O.Z)(u)).length,p=!1;for(null==n&&(i=o(s=a())),c=0;c<=f;++c)!(c=f;--p)u.point(m[p],b[p]);u.lineEnd(),u.areaEnd()}}v&&(m[s]=+t(h,s,l),b[s]=+e(h,s,l),u.point(n?+n(h,s,l):m[s],r?+r(h,s,l):b[s]))}if(d)return u=null,d+""||null}function s(){return k().defined(o).curve(a).context(i)}return t="function"==typeof t?t:void 0===t?P:(0,j.Z)(+t),e="function"==typeof e?e:void 0===e?(0,j.Z)(0):(0,j.Z)(+e),r="function"==typeof r?r:void 0===r?E:(0,j.Z)(+r),l.x=function(e){return arguments.length?(t="function"==typeof e?e:(0,j.Z)(+e),n=null,l):t},l.x0=function(e){return arguments.length?(t="function"==typeof e?e:(0,j.Z)(+e),l):t},l.x1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:(0,j.Z)(+t),l):n},l.y=function(t){return arguments.length?(e="function"==typeof t?t:(0,j.Z)(+t),r=null,l):e},l.y0=function(t){return arguments.length?(e="function"==typeof t?t:(0,j.Z)(+t),l):e},l.y1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:(0,j.Z)(+t),l):r},l.lineX0=l.lineY0=function(){return s().x(t).y(e)},l.lineY1=function(){return s().x(t).y(r)},l.lineX1=function(){return s().x(n).y(e)},l.defined=function(t){return arguments.length?(o="function"==typeof t?t:(0,j.Z)(!!t),l):o},l.curve=function(t){return arguments.length?(a=t,null!=i&&(u=a(i)),l):a},l.context=function(t){return arguments.length?(null==t?i=u=null:u=a(i=t),l):i},l}var M=r(75551),_=r.n(M),T=r(86757),C=r.n(T),N=r(61994),D=r(41637),I=r(82944),L=r(16630);function B(t){return(B="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function R(){return(R=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);r=0?1:-1,c=r>=0?1:-1,l=n>=0&&r>=0||n<0&&r<0?1:0;if(a>0&&o instanceof Array){for(var s=[0,0,0,0],f=0;f<4;f++)s[f]=o[f]>a?a:o[f];i="M".concat(t,",").concat(e+u*s[0]),s[0]>0&&(i+="A ".concat(s[0],",").concat(s[0],",0,0,").concat(l,",").concat(t+c*s[0],",").concat(e)),i+="L ".concat(t+r-c*s[1],",").concat(e),s[1]>0&&(i+="A ".concat(s[1],",").concat(s[1],",0,0,").concat(l,",\n ").concat(t+r,",").concat(e+u*s[1])),i+="L ".concat(t+r,",").concat(e+n-u*s[2]),s[2]>0&&(i+="A ".concat(s[2],",").concat(s[2],",0,0,").concat(l,",\n ").concat(t+r-c*s[2],",").concat(e+n)),i+="L ".concat(t+c*s[3],",").concat(e+n),s[3]>0&&(i+="A ".concat(s[3],",").concat(s[3],",0,0,").concat(l,",\n ").concat(t,",").concat(e+n-u*s[3])),i+="Z"}else if(a>0&&o===+o&&o>0){var p=Math.min(a,o);i="M ".concat(t,",").concat(e+u*p,"\n A ").concat(p,",").concat(p,",0,0,").concat(l,",").concat(t+c*p,",").concat(e,"\n L ").concat(t+r-c*p,",").concat(e,"\n A ").concat(p,",").concat(p,",0,0,").concat(l,",").concat(t+r,",").concat(e+u*p,"\n L ").concat(t+r,",").concat(e+n-u*p,"\n A ").concat(p,",").concat(p,",0,0,").concat(l,",").concat(t+r-c*p,",").concat(e+n,"\n L ").concat(t+c*p,",").concat(e+n,"\n A ").concat(p,",").concat(p,",0,0,").concat(l,",").concat(t,",").concat(e+n-u*p," Z")}else i="M ".concat(t,",").concat(e," h ").concat(r," v ").concat(n," h ").concat(-r," Z");return i},h=function(t,e){if(!t||!e)return!1;var r=t.x,n=t.y,o=e.x,i=e.y,a=e.width,u=e.height;return!!(Math.abs(a)>0&&Math.abs(u)>0)&&r>=Math.min(o,o+a)&&r<=Math.max(o,o+a)&&n>=Math.min(i,i+u)&&n<=Math.max(i,i+u)},d={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},y=function(t){var e,r=f(f({},d),t),u=(0,n.useRef)(),s=function(t){if(Array.isArray(t))return t}(e=(0,n.useState)(-1))||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{for(i=(r=r.call(t)).next;!(c=(n=i.call(r)).done)&&(u.push(n.value),2!==u.length);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(e,2)||function(t,e){if(t){if("string"==typeof t)return l(t,2);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return l(t,2)}}(e,2)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(),h=s[0],y=s[1];(0,n.useEffect)(function(){if(u.current&&u.current.getTotalLength)try{var t=u.current.getTotalLength();t&&y(t)}catch(t){}},[]);var v=r.x,m=r.y,b=r.width,g=r.height,x=r.radius,w=r.className,O=r.animationEasing,j=r.animationDuration,S=r.animationBegin,P=r.isAnimationActive,E=r.isUpdateAnimationActive;if(v!==+v||m!==+m||b!==+b||g!==+g||0===b||0===g)return null;var k=(0,o.Z)("recharts-rectangle",w);return E?n.createElement(i.ZP,{canBegin:h>0,from:{width:b,height:g,x:v,y:m},to:{width:b,height:g,x:v,y:m},duration:j,animationEasing:O,isActive:E},function(t){var e=t.width,o=t.height,l=t.x,s=t.y;return n.createElement(i.ZP,{canBegin:h>0,from:"0px ".concat(-1===h?1:h,"px"),to:"".concat(h,"px 0px"),attributeName:"strokeDasharray",begin:S,duration:j,isActive:P,easing:O},n.createElement("path",c({},(0,a.L6)(r,!0),{className:k,d:p(l,s,e,o,x),ref:u})))}):n.createElement("path",c({},(0,a.L6)(r,!0),{className:k,d:p(v,m,b,g,x)}))}},60474:function(t,e,r){"use strict";r.d(e,{L:function(){return v}});var n=r(2265),o=r(61994),i=r(82944),a=r(39206),u=r(16630);function c(t){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function l(){return(l=Object.assign?Object.assign.bind():function(t){for(var e=1;e180),",").concat(+(c>s),",\n ").concat(p.x,",").concat(p.y,"\n ");if(o>0){var d=(0,a.op)(r,n,o,c),y=(0,a.op)(r,n,o,s);h+="L ".concat(y.x,",").concat(y.y,"\n A ").concat(o,",").concat(o,",0,\n ").concat(+(Math.abs(l)>180),",").concat(+(c<=s),",\n ").concat(d.x,",").concat(d.y," Z")}else h+="L ".concat(r,",").concat(n," Z");return h},d=function(t){var e=t.cx,r=t.cy,n=t.innerRadius,o=t.outerRadius,i=t.cornerRadius,a=t.forceCornerRadius,c=t.cornerIsExternal,l=t.startAngle,s=t.endAngle,f=(0,u.uY)(s-l),d=p({cx:e,cy:r,radius:o,angle:l,sign:f,cornerRadius:i,cornerIsExternal:c}),y=d.circleTangency,v=d.lineTangency,m=d.theta,b=p({cx:e,cy:r,radius:o,angle:s,sign:-f,cornerRadius:i,cornerIsExternal:c}),g=b.circleTangency,x=b.lineTangency,w=b.theta,O=c?Math.abs(l-s):Math.abs(l-s)-m-w;if(O<0)return a?"M ".concat(v.x,",").concat(v.y,"\n a").concat(i,",").concat(i,",0,0,1,").concat(2*i,",0\n a").concat(i,",").concat(i,",0,0,1,").concat(-(2*i),",0\n "):h({cx:e,cy:r,innerRadius:n,outerRadius:o,startAngle:l,endAngle:s});var j="M ".concat(v.x,",").concat(v.y,"\n A").concat(i,",").concat(i,",0,0,").concat(+(f<0),",").concat(y.x,",").concat(y.y,"\n A").concat(o,",").concat(o,",0,").concat(+(O>180),",").concat(+(f<0),",").concat(g.x,",").concat(g.y,"\n A").concat(i,",").concat(i,",0,0,").concat(+(f<0),",").concat(x.x,",").concat(x.y,"\n ");if(n>0){var S=p({cx:e,cy:r,radius:n,angle:l,sign:f,isExternal:!0,cornerRadius:i,cornerIsExternal:c}),P=S.circleTangency,E=S.lineTangency,k=S.theta,A=p({cx:e,cy:r,radius:n,angle:s,sign:-f,isExternal:!0,cornerRadius:i,cornerIsExternal:c}),M=A.circleTangency,_=A.lineTangency,T=A.theta,C=c?Math.abs(l-s):Math.abs(l-s)-k-T;if(C<0&&0===i)return"".concat(j,"L").concat(e,",").concat(r,"Z");j+="L".concat(_.x,",").concat(_.y,"\n A").concat(i,",").concat(i,",0,0,").concat(+(f<0),",").concat(M.x,",").concat(M.y,"\n A").concat(n,",").concat(n,",0,").concat(+(C>180),",").concat(+(f>0),",").concat(P.x,",").concat(P.y,"\n A").concat(i,",").concat(i,",0,0,").concat(+(f<0),",").concat(E.x,",").concat(E.y,"Z")}else j+="L".concat(e,",").concat(r,"Z");return j},y={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},v=function(t){var e,r=f(f({},y),t),a=r.cx,c=r.cy,s=r.innerRadius,p=r.outerRadius,v=r.cornerRadius,m=r.forceCornerRadius,b=r.cornerIsExternal,g=r.startAngle,x=r.endAngle,w=r.className;if(p0&&360>Math.abs(g-x)?d({cx:a,cy:c,innerRadius:s,outerRadius:p,cornerRadius:Math.min(S,j/2),forceCornerRadius:m,cornerIsExternal:b,startAngle:g,endAngle:x}):h({cx:a,cy:c,innerRadius:s,outerRadius:p,startAngle:g,endAngle:x}),n.createElement("path",l({},(0,i.L6)(r,!0),{className:O,d:e,role:"img"}))}},14870:function(t,e,r){"use strict";r.d(e,{v:function(){return N}});var n=r(2265),o=r(75551),i=r.n(o);let a=Math.cos,u=Math.sin,c=Math.sqrt,l=Math.PI,s=2*l;var f={draw(t,e){let r=c(e/l);t.moveTo(r,0),t.arc(0,0,r,0,s)}};let p=c(1/3),h=2*p,d=u(l/10)/u(7*l/10),y=u(s/10)*d,v=-a(s/10)*d,m=c(3),b=c(3)/2,g=1/c(12),x=(g/2+1)*3;var w=r(76115),O=r(67790);c(3),c(3);var j=r(61994),S=r(82944);function P(t){return(P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var E=["type","size","sizeType"];function k(){return(k=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,E)),{},{type:o,size:u,sizeType:l}),p=s.className,h=s.cx,d=s.cy,y=(0,S.L6)(s,!0);return h===+h&&d===+d&&u===+u?n.createElement("path",k({},y,{className:(0,j.Z)("recharts-symbols",p),transform:"translate(".concat(h,", ").concat(d,")"),d:(e=_["symbol".concat(i()(o))]||f,(function(t,e){let r=null,n=(0,O.d)(o);function o(){let o;if(r||(r=o=n()),t.apply(this,arguments).draw(r,+e.apply(this,arguments)),o)return r=null,o+""||null}return t="function"==typeof t?t:(0,w.Z)(t||f),e="function"==typeof e?e:(0,w.Z)(void 0===e?64:+e),o.type=function(e){return arguments.length?(t="function"==typeof e?e:(0,w.Z)(e),o):t},o.size=function(t){return arguments.length?(e="function"==typeof t?t:(0,w.Z)(+t),o):e},o.context=function(t){return arguments.length?(r=null==t?null:t,o):r},o})().type(e).size(C(u,l,o))())})):null};N.registerSymbol=function(t,e){_["symbol".concat(i()(t))]=e}},11638:function(t,e,r){"use strict";r.d(e,{bn:function(){return C},a3:function(){return z},lT:function(){return N},V$:function(){return D},w7:function(){return I}});var n=r(2265),o=r(86757),i=r.n(o),a=r(90231),u=r.n(a),c=r(24342),l=r.n(c),s=r(21652),f=r.n(s),p=r(73649),h=r(61994),d=r(84735),y=r(82944);function v(t){return(v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function m(){return(m=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=Array(e);r0,from:{upperWidth:0,lowerWidth:0,height:p,x:c,y:l},to:{upperWidth:s,lowerWidth:f,height:p,x:c,y:l},duration:j,animationEasing:g,isActive:P},function(t){var e=t.upperWidth,i=t.lowerWidth,u=t.height,c=t.x,l=t.y;return n.createElement(d.ZP,{canBegin:a>0,from:"0px ".concat(-1===a?1:a,"px"),to:"".concat(a,"px 0px"),attributeName:"strokeDasharray",begin:S,duration:j,easing:g},n.createElement("path",m({},(0,y.L6)(r,!0),{className:E,d:w(c,l,e,i,u),ref:o})))}):n.createElement("g",null,n.createElement("path",m({},(0,y.L6)(r,!0),{className:E,d:w(c,l,s,f,p)})))},S=r(60474),P=r(9841),E=r(14870),k=["option","shapeType","propTransformer","activeClassName","isActive"];function A(t){return(A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function M(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function _(t){for(var e=1;e=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,k);if((0,n.isValidElement)(r))e=(0,n.cloneElement)(r,_(_({},f),(0,n.isValidElement)(r)?r.props:r));else if(i()(r))e=r(f);else if(u()(r)&&!l()(r)){var p=(void 0===a?function(t,e){return _(_({},e),t)}:a)(r,f);e=n.createElement(T,{shapeType:o,elementProps:p})}else e=n.createElement(T,{shapeType:o,elementProps:f});return s?n.createElement(P.m,{className:void 0===c?"recharts-active-shape":c},e):e}function N(t,e){return null!=e&&"trapezoids"in t.props}function D(t,e){return null!=e&&"sectors"in t.props}function I(t,e){return null!=e&&"points"in t.props}function L(t,e){var r,n,o=t.x===(null==e||null===(r=e.labelViewBox)||void 0===r?void 0:r.x)||t.x===e.x,i=t.y===(null==e||null===(n=e.labelViewBox)||void 0===n?void 0:n.y)||t.y===e.y;return o&&i}function B(t,e){var r=t.endAngle===e.endAngle,n=t.startAngle===e.startAngle;return r&&n}function R(t,e){var r=t.x===e.x,n=t.y===e.y,o=t.z===e.z;return r&&n&&o}function z(t){var e,r,n,o=t.activeTooltipItem,i=t.graphicalItem,a=t.itemData,u=(N(i,o)?e="trapezoids":D(i,o)?e="sectors":I(i,o)&&(e="points"),e),c=N(i,o)?null===(r=o.tooltipPayload)||void 0===r||null===(r=r[0])||void 0===r||null===(r=r.payload)||void 0===r?void 0:r.payload:D(i,o)?null===(n=o.tooltipPayload)||void 0===n||null===(n=n[0])||void 0===n||null===(n=n.payload)||void 0===n?void 0:n.payload:I(i,o)?o.payload:{},l=a.filter(function(t,e){var r=f()(c,t),n=i.props[u].filter(function(t){var e;return(N(i,o)?e=L:D(i,o)?e=B:I(i,o)&&(e=R),e)(t,o)}),a=i.props[u].indexOf(n[n.length-1]);return r&&e===a});return a.indexOf(l[l.length-1])}},25311:function(t,e,r){"use strict";r.d(e,{Ky:function(){return w},O1:function(){return b},_b:function(){return g},t9:function(){return m},xE:function(){return O}});var n=r(41443),o=r.n(n),i=r(32242),a=r.n(i),u=r(85355),c=r(82944),l=r(16630),s=r(31699);function f(t){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function p(t,e){for(var r=0;r0&&(A=Math.min((t||0)-(M[e-1]||0),A))}),Number.isFinite(A)){var _=A/k,T="vertical"===g.layout?r.height:r.width;if("gap"===g.padding&&(c=_*T/2),"no-gap"===g.padding){var C=(0,l.h1)(t.barCategoryGap,_*T),N=_*T/2;c=N-C-(N-C)/T*C}}}s="xAxis"===n?[r.left+(j.left||0)+(c||0),r.left+r.width-(j.right||0)-(c||0)]:"yAxis"===n?"horizontal"===f?[r.top+r.height-(j.bottom||0),r.top+(j.top||0)]:[r.top+(j.top||0)+(c||0),r.top+r.height-(j.bottom||0)-(c||0)]:g.range,P&&(s=[s[1],s[0]]);var D=(0,u.Hq)(g,o,m),I=D.scale,L=D.realScaleType;I.domain(w).range(s),(0,u.zF)(I);var B=(0,u.g$)(I,d(d({},g),{},{realScaleType:L}));"xAxis"===n?(b="top"===x&&!S||"bottom"===x&&S,p=r.left,h=v[E]-b*g.height):"yAxis"===n&&(b="left"===x&&!S||"right"===x&&S,p=v[E]-b*g.width,h=r.top);var R=d(d(d({},g),B),{},{realScaleType:L,x:p,y:h,scale:I,width:"xAxis"===n?r.width:g.width,height:"yAxis"===n?r.height:g.height});return R.bandSize=(0,u.zT)(R,B),g.hide||"xAxis"!==n?g.hide||(v[E]+=(b?-1:1)*R.width):v[E]+=(b?-1:1)*R.height,d(d({},i),{},y({},a,R))},{})},b=function(t,e){var r=t.x,n=t.y,o=e.x,i=e.y;return{x:Math.min(r,o),y:Math.min(n,i),width:Math.abs(o-r),height:Math.abs(i-n)}},g=function(t){return b({x:t.x1,y:t.y1},{x:t.x2,y:t.y2})},x=function(){var t,e;function r(t){!function(t,e){if(!(t instanceof e))throw TypeError("Cannot call a class as a function")}(this,r),this.scale=t}return t=[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.bandAware,n=e.position;if(void 0!==t){if(n)switch(n){case"start":default:return this.scale(t);case"middle":var o=this.bandwidth?this.bandwidth()/2:0;return this.scale(t)+o;case"end":var i=this.bandwidth?this.bandwidth():0;return this.scale(t)+i}if(r){var a=this.bandwidth?this.bandwidth()/2:0;return this.scale(t)+a}return this.scale(t)}}},{key:"isInRange",value:function(t){var e=this.range(),r=e[0],n=e[e.length-1];return r<=n?t>=r&&t<=n:t>=n&&t<=r}}],e=[{key:"create",value:function(t){return new r(t)}}],t&&p(r.prototype,t),e&&p(r,e),Object.defineProperty(r,"prototype",{writable:!1}),r}();y(x,"EPS",1e-4);var w=function(t){var e=Object.keys(t).reduce(function(e,r){return d(d({},e),{},y({},r,x.create(t[r])))},{});return d(d({},e),{},{apply:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.bandAware,i=r.position;return o()(t,function(t,r){return e[r].apply(t,{bandAware:n,position:i})})},isInRange:function(t){return a()(t,function(t,r){return e[r].isInRange(t)})}})},O=function(t){var e=t.width,r=t.height,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=(n%180+180)%180*Math.PI/180,i=Math.atan(r/e);return Math.abs(o>i&&otx(e,t()).base(e.base()),tj.o.apply(e,arguments),e}},scaleOrdinal:function(){return tX.Z},scalePoint:function(){return f.x},scalePow:function(){return tJ},scaleQuantile:function(){return function t(){var e,r=[],n=[],o=[];function i(){var t=0,e=Math.max(1,n.length);for(o=Array(e-1);++t=1)return+r(t[n-1],n-1,t);var n,o=(n-1)*e,i=Math.floor(o),a=+r(t[i],i,t);return a+(+r(t[i+1],i+1,t)-a)*(o-i)}}(r,t/e);return a}function a(t){return null==t||isNaN(t=+t)?e:n[P(o,t)]}return a.invertExtent=function(t){var e=n.indexOf(t);return e<0?[NaN,NaN]:[e>0?o[e-1]:r[0],e=o?[i[o-1],n]:[i[e-1],i[e]]},u.unknown=function(t){return arguments.length&&(e=t),u},u.thresholds=function(){return i.slice()},u.copy=function(){return t().domain([r,n]).range(a).unknown(e)},tj.o.apply(tI(u),arguments)}},scaleRadial:function(){return function t(){var e,r=tO(),n=[0,1],o=!1;function i(t){var n,i=Math.sign(n=r(t))*Math.sqrt(Math.abs(n));return isNaN(i)?e:o?Math.round(i):i}return i.invert=function(t){return r.invert(t1(t))},i.domain=function(t){return arguments.length?(r.domain(t),i):r.domain()},i.range=function(t){return arguments.length?(r.range((n=Array.from(t,td)).map(t1)),i):n.slice()},i.rangeRound=function(t){return i.range(t).round(!0)},i.round=function(t){return arguments.length?(o=!!t,i):o},i.clamp=function(t){return arguments.length?(r.clamp(t),i):r.clamp()},i.unknown=function(t){return arguments.length?(e=t,i):e},i.copy=function(){return t(r.domain(),n).round(o).clamp(r.clamp()).unknown(e)},tj.o.apply(i,arguments),tI(i)}},scaleSequential:function(){return function t(){var e=tI(rX()(tv));return e.copy=function(){return rG(e,t())},tj.O.apply(e,arguments)}},scaleSequentialLog:function(){return function t(){var e=tZ(rX()).domain([1,10]);return e.copy=function(){return rG(e,t()).base(e.base())},tj.O.apply(e,arguments)}},scaleSequentialPow:function(){return rV},scaleSequentialQuantile:function(){return function t(){var e=[],r=tv;function n(t){if(null!=t&&!isNaN(t=+t))return r((P(e,t,1)-1)/(e.length-1))}return n.domain=function(t){if(!arguments.length)return e.slice();for(let r of(e=[],t))null==r||isNaN(r=+r)||e.push(r);return e.sort(g),n},n.interpolator=function(t){return arguments.length?(r=t,n):r},n.range=function(){return e.map((t,n)=>r(n/(e.length-1)))},n.quantiles=function(t){return Array.from({length:t+1},(r,n)=>(function(t,e,r){if(!(!(n=(t=Float64Array.from(function*(t,e){if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(yield e);else{let r=-1;for(let n of t)null!=(n=e(n,++r,t))&&(n=+n)>=n&&(yield n)}}(t,void 0))).length)||isNaN(e=+e))){if(e<=0||n<2)return t5(t);if(e>=1)return t2(t);var n,o=(n-1)*e,i=Math.floor(o),a=t2((function t(e,r,n=0,o=1/0,i){if(r=Math.floor(r),n=Math.floor(Math.max(0,n)),o=Math.floor(Math.min(e.length-1,o)),!(n<=r&&r<=o))return e;for(i=void 0===i?t6:function(t=g){if(t===g)return t6;if("function"!=typeof t)throw TypeError("compare is not a function");return(e,r)=>{let n=t(e,r);return n||0===n?n:(0===t(r,r))-(0===t(e,e))}}(i);o>n;){if(o-n>600){let a=o-n+1,u=r-n+1,c=Math.log(a),l=.5*Math.exp(2*c/3),s=.5*Math.sqrt(c*l*(a-l)/a)*(u-a/2<0?-1:1),f=Math.max(n,Math.floor(r-u*l/a+s)),p=Math.min(o,Math.floor(r+(a-u)*l/a+s));t(e,r,f,p,i)}let a=e[r],u=n,c=o;for(t3(e,n,r),i(e[o],a)>0&&t3(e,n,o);ui(e[u],a);)++u;for(;i(e[c],a)>0;)--c}0===i(e[n],a)?t3(e,n,c):t3(e,++c,o),c<=r&&(n=c+1),r<=c&&(o=c-1)}return e})(t,i).subarray(0,i+1));return a+(t5(t.subarray(i+1))-a)*(o-i)}})(e,n/t))},n.copy=function(){return t(r).domain(e)},tj.O.apply(n,arguments)}},scaleSequentialSqrt:function(){return rK},scaleSequentialSymlog:function(){return function t(){var e=tH(rX());return e.copy=function(){return rG(e,t()).constant(e.constant())},tj.O.apply(e,arguments)}},scaleSqrt:function(){return t0},scaleSymlog:function(){return function t(){var e=tH(tw());return e.copy=function(){return tx(e,t()).constant(e.constant())},tj.o.apply(e,arguments)}},scaleThreshold:function(){return function t(){var e,r=[.5],n=[0,1],o=1;function i(t){return null!=t&&t<=t?n[P(r,t,0,o)]:e}return i.domain=function(t){return arguments.length?(o=Math.min((r=Array.from(t)).length,n.length-1),i):r.slice()},i.range=function(t){return arguments.length?(n=Array.from(t),o=Math.min(r.length,n.length-1),i):n.slice()},i.invertExtent=function(t){var e=n.indexOf(t);return[r[e-1],r[e]]},i.unknown=function(t){return arguments.length?(e=t,i):e},i.copy=function(){return t().domain(r).range(n).unknown(e)},tj.o.apply(i,arguments)}},scaleTime:function(){return rY},scaleUtc:function(){return rH},tickFormat:function(){return tD}});var f=r(55284);let p=Math.sqrt(50),h=Math.sqrt(10),d=Math.sqrt(2);function y(t,e,r){let n,o,i;let a=(e-t)/Math.max(0,r),u=Math.floor(Math.log10(a)),c=a/Math.pow(10,u),l=c>=p?10:c>=h?5:c>=d?2:1;return(u<0?(n=Math.round(t*(i=Math.pow(10,-u)/l)),o=Math.round(e*i),n/ie&&--o,i=-i):(n=Math.round(t/(i=Math.pow(10,u)*l)),o=Math.round(e/i),n*ie&&--o),o0))return[];if(t===e)return[t];let n=e=o))return[];let u=i-o+1,c=Array(u);if(n){if(a<0)for(let t=0;te?1:t>=e?0:NaN}function x(t,e){return null==t||null==e?NaN:et?1:e>=t?0:NaN}function w(t){let e,r,n;function o(t,n,o=0,i=t.length){if(o>>1;0>r(t[e],n)?o=e+1:i=e}while(og(t(e),r),n=(e,r)=>t(e)-r):(e=t===g||t===x?t:O,r=t,n=t),{left:o,center:function(t,e,r=0,i=t.length){let a=o(t,e,r,i-1);return a>r&&n(t[a-1],e)>-n(t[a],e)?a-1:a},right:function(t,n,o=0,i=t.length){if(o>>1;0>=r(t[e],n)?o=e+1:i=e}while(o>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===r?Z(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===r?Z(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=N.exec(t))?new Y(e[1],e[2],e[3],1):(e=D.exec(t))?new Y(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=I.exec(t))?Z(e[1],e[2],e[3],e[4]):(e=L.exec(t))?Z(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=B.exec(t))?Q(e[1],e[2]/100,e[3]/100,1):(e=R.exec(t))?Q(e[1],e[2]/100,e[3]/100,e[4]):z.hasOwnProperty(t)?q(z[t]):"transparent"===t?new Y(NaN,NaN,NaN,0):null}function q(t){return new Y(t>>16&255,t>>8&255,255&t,1)}function Z(t,e,r,n){return n<=0&&(t=e=r=NaN),new Y(t,e,r,n)}function W(t,e,r,n){var o;return 1==arguments.length?((o=t)instanceof A||(o=$(o)),o)?new Y((o=o.rgb()).r,o.g,o.b,o.opacity):new Y:new Y(t,e,r,null==n?1:n)}function Y(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}function H(){return`#${K(this.r)}${K(this.g)}${K(this.b)}`}function X(){let t=G(this.opacity);return`${1===t?"rgb(":"rgba("}${V(this.r)}, ${V(this.g)}, ${V(this.b)}${1===t?")":`, ${t})`}`}function G(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function V(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function K(t){return((t=V(t))<16?"0":"")+t.toString(16)}function Q(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new tt(t,e,r,n)}function J(t){if(t instanceof tt)return new tt(t.h,t.s,t.l,t.opacity);if(t instanceof A||(t=$(t)),!t)return new tt;if(t instanceof tt)return t;var e=(t=t.rgb()).r/255,r=t.g/255,n=t.b/255,o=Math.min(e,r,n),i=Math.max(e,r,n),a=NaN,u=i-o,c=(i+o)/2;return u?(a=e===i?(r-n)/u+(r0&&c<1?0:a,new tt(a,u,c,t.opacity)}function tt(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}function te(t){return(t=(t||0)%360)<0?t+360:t}function tr(t){return Math.max(0,Math.min(1,t||0))}function tn(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}function to(t,e,r,n,o){var i=t*t,a=i*t;return((1-3*t+3*i-a)*e+(4-6*i+3*a)*r+(1+3*t+3*i-3*a)*n+a*o)/6}E(A,$,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:U,formatHex:U,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return J(this).formatHsl()},formatRgb:F,toString:F}),E(Y,W,k(A,{brighter(t){return t=null==t?1.4285714285714286:Math.pow(1.4285714285714286,t),new Y(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?.7:Math.pow(.7,t),new Y(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new Y(V(this.r),V(this.g),V(this.b),G(this.opacity))},displayable(){return -.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:H,formatHex:H,formatHex8:function(){return`#${K(this.r)}${K(this.g)}${K(this.b)}${K((isNaN(this.opacity)?1:this.opacity)*255)}`},formatRgb:X,toString:X})),E(tt,function(t,e,r,n){return 1==arguments.length?J(t):new tt(t,e,r,null==n?1:n)},k(A,{brighter(t){return t=null==t?1.4285714285714286:Math.pow(1.4285714285714286,t),new tt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?.7:Math.pow(.7,t),new tt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,o=2*r-n;return new Y(tn(t>=240?t-240:t+120,o,n),tn(t,o,n),tn(t<120?t+240:t-120,o,n),this.opacity)},clamp(){return new tt(te(this.h),tr(this.s),tr(this.l),G(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let t=G(this.opacity);return`${1===t?"hsl(":"hsla("}${te(this.h)}, ${100*tr(this.s)}%, ${100*tr(this.l)}%${1===t?")":`, ${t})`}`}}));var ti=t=>()=>t;function ta(t,e){var r=e-t;return r?function(e){return t+e*r}:ti(isNaN(t)?e:t)}var tu=function t(e){var r,n=1==(r=+(r=e))?ta:function(t,e){var n,o,i;return e-t?(n=t,o=e,n=Math.pow(n,i=r),o=Math.pow(o,i)-n,i=1/i,function(t){return Math.pow(n+t*o,i)}):ti(isNaN(t)?e:t)};function o(t,e){var r=n((t=W(t)).r,(e=W(e)).r),o=n(t.g,e.g),i=n(t.b,e.b),a=ta(t.opacity,e.opacity);return function(e){return t.r=r(e),t.g=o(e),t.b=i(e),t.opacity=a(e),t+""}}return o.gamma=t,o}(1);function tc(t){return function(e){var r,n,o=e.length,i=Array(o),a=Array(o),u=Array(o);for(r=0;r=1?(r=1,e-1):Math.floor(r*e),o=t[n],i=t[n+1],a=n>0?t[n-1]:2*o-i,u=nu&&(a=e.slice(u,a),l[c]?l[c]+=a:l[++c]=a),(o=o[0])===(i=i[0])?l[c]?l[c]+=i:l[++c]=i:(l[++c]=null,s.push({i:c,x:tl(o,i)})),u=tf.lastIndex;return ue&&(r=t,t=e,e=r),l=function(r){return Math.max(t,Math.min(e,r))}),n=c>2?tg:tb,o=i=null,f}function f(e){return null==e||isNaN(e=+e)?r:(o||(o=n(a.map(t),u,c)))(t(l(e)))}return f.invert=function(r){return l(e((i||(i=n(u,a.map(t),tl)))(r)))},f.domain=function(t){return arguments.length?(a=Array.from(t,td),s()):a.slice()},f.range=function(t){return arguments.length?(u=Array.from(t),s()):u.slice()},f.rangeRound=function(t){return u=Array.from(t),c=th,s()},f.clamp=function(t){return arguments.length?(l=!!t||tv,s()):l!==tv},f.interpolate=function(t){return arguments.length?(c=t,s()):c},f.unknown=function(t){return arguments.length?(r=t,f):r},function(r,n){return t=r,e=n,s()}}function tO(){return tw()(tv,tv)}var tj=r(89999),tS=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function tP(t){var e;if(!(e=tS.exec(t)))throw Error("invalid format: "+t);return new tE({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function tE(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function tk(t,e){if((r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var r,n=t.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+t.slice(r+1)]}function tA(t){return(t=tk(Math.abs(t)))?t[1]:NaN}function tM(t,e){var r=tk(t,e);if(!r)return t+"";var n=r[0],o=r[1];return o<0?"0."+Array(-o).join("0")+n:n.length>o+1?n.slice(0,o+1)+"."+n.slice(o+1):n+Array(o-n.length+2).join("0")}tP.prototype=tE.prototype,tE.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var t_={"%":(t,e)=>(100*t).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>tM(100*t,e),r:tM,s:function(t,e){var r=tk(t,e);if(!r)return t+"";var o=r[0],i=r[1],a=i-(n=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,u=o.length;return a===u?o:a>u?o+Array(a-u+1).join("0"):a>0?o.slice(0,a)+"."+o.slice(a):"0."+Array(1-a).join("0")+tk(t,Math.max(0,e+a-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function tT(t){return t}var tC=Array.prototype.map,tN=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"];function tD(t,e,r,n){var o,u,c=b(t,e,r);switch((n=tP(null==n?",f":n)).type){case"s":var l=Math.max(Math.abs(t),Math.abs(e));return null!=n.precision||isNaN(u=Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(tA(l)/3)))-tA(Math.abs(c))))||(n.precision=u),a(n,l);case"":case"e":case"g":case"p":case"r":null!=n.precision||isNaN(u=Math.max(0,tA(Math.abs(Math.max(Math.abs(t),Math.abs(e)))-(o=Math.abs(o=c)))-tA(o))+1)||(n.precision=u-("e"===n.type));break;case"f":case"%":null!=n.precision||isNaN(u=Math.max(0,-tA(Math.abs(c))))||(n.precision=u-("%"===n.type)*2)}return i(n)}function tI(t){var e=t.domain;return t.ticks=function(t){var r=e();return v(r[0],r[r.length-1],null==t?10:t)},t.tickFormat=function(t,r){var n=e();return tD(n[0],n[n.length-1],null==t?10:t,r)},t.nice=function(r){null==r&&(r=10);var n,o,i=e(),a=0,u=i.length-1,c=i[a],l=i[u],s=10;for(l0;){if((o=m(c,l,r))===n)return i[a]=c,i[u]=l,e(i);if(o>0)c=Math.floor(c/o)*o,l=Math.ceil(l/o)*o;else if(o<0)c=Math.ceil(c*o)/o,l=Math.floor(l*o)/o;else break;n=o}return t},t}function tL(){var t=tO();return t.copy=function(){return tx(t,tL())},tj.o.apply(t,arguments),tI(t)}function tB(t,e){t=t.slice();var r,n=0,o=t.length-1,i=t[n],a=t[o];return a-t(-e,r)}function tZ(t){let e,r;let n=t(tR,tz),o=n.domain,a=10;function u(){var i,u;return e=(i=a)===Math.E?Math.log:10===i&&Math.log10||2===i&&Math.log2||(i=Math.log(i),t=>Math.log(t)/i),r=10===(u=a)?t$:u===Math.E?Math.exp:t=>Math.pow(u,t),o()[0]<0?(e=tq(e),r=tq(r),t(tU,tF)):t(tR,tz),n}return n.base=function(t){return arguments.length?(a=+t,u()):a},n.domain=function(t){return arguments.length?(o(t),u()):o()},n.ticks=t=>{let n,i;let u=o(),c=u[0],l=u[u.length-1],s=l0){for(;f<=p;++f)for(n=1;nl)break;d.push(i)}}else for(;f<=p;++f)for(n=a-1;n>=1;--n)if(!((i=f>0?n/r(-f):n*r(f))l)break;d.push(i)}2*d.length{if(null==t&&(t=10),null==o&&(o=10===a?"s":","),"function"!=typeof o&&(a%1||null!=(o=tP(o)).precision||(o.trim=!0),o=i(o)),t===1/0)return o;let u=Math.max(1,a*t/n.ticks().length);return t=>{let n=t/r(Math.round(e(t)));return n*ao(tB(o(),{floor:t=>r(Math.floor(e(t))),ceil:t=>r(Math.ceil(e(t)))})),n}function tW(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function tY(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function tH(t){var e=1,r=t(tW(1),tY(e));return r.constant=function(r){return arguments.length?t(tW(e=+r),tY(e)):e},tI(r)}i=(o=function(t){var e,r,o,i=void 0===t.grouping||void 0===t.thousands?tT:(e=tC.call(t.grouping,Number),r=t.thousands+"",function(t,n){for(var o=t.length,i=[],a=0,u=e[0],c=0;o>0&&u>0&&(c+u+1>n&&(u=Math.max(1,n-c)),i.push(t.substring(o-=u,o+u)),!((c+=u+1)>n));)u=e[a=(a+1)%e.length];return i.reverse().join(r)}),a=void 0===t.currency?"":t.currency[0]+"",u=void 0===t.currency?"":t.currency[1]+"",c=void 0===t.decimal?".":t.decimal+"",l=void 0===t.numerals?tT:(o=tC.call(t.numerals,String),function(t){return t.replace(/[0-9]/g,function(t){return o[+t]})}),s=void 0===t.percent?"%":t.percent+"",f=void 0===t.minus?"−":t.minus+"",p=void 0===t.nan?"NaN":t.nan+"";function h(t){var e=(t=tP(t)).fill,r=t.align,o=t.sign,h=t.symbol,d=t.zero,y=t.width,v=t.comma,m=t.precision,b=t.trim,g=t.type;"n"===g?(v=!0,g="g"):t_[g]||(void 0===m&&(m=12),b=!0,g="g"),(d||"0"===e&&"="===r)&&(d=!0,e="0",r="=");var x="$"===h?a:"#"===h&&/[boxX]/.test(g)?"0"+g.toLowerCase():"",w="$"===h?u:/[%p]/.test(g)?s:"",O=t_[g],j=/[defgprs%]/.test(g);function S(t){var a,u,s,h=x,S=w;if("c"===g)S=O(t)+S,t="";else{var P=(t=+t)<0||1/t<0;if(t=isNaN(t)?p:O(Math.abs(t),m),b&&(t=function(t){e:for(var e,r=t.length,n=1,o=-1;n0&&(o=0)}return o>0?t.slice(0,o)+t.slice(e+1):t}(t)),P&&0==+t&&"+"!==o&&(P=!1),h=(P?"("===o?o:f:"-"===o||"("===o?"":o)+h,S=("s"===g?tN[8+n/3]:"")+S+(P&&"("===o?")":""),j){for(a=-1,u=t.length;++a(s=t.charCodeAt(a))||s>57){S=(46===s?c+t.slice(a+1):t.slice(a))+S,t=t.slice(0,a);break}}}v&&!d&&(t=i(t,1/0));var E=h.length+t.length+S.length,k=E>1)+h+t+S+k.slice(E);break;default:t=k+h+t+S}return l(t)}return m=void 0===m?6:/[gprs]/.test(g)?Math.max(1,Math.min(21,m)):Math.max(0,Math.min(20,m)),S.toString=function(){return t+""},S}return{format:h,formatPrefix:function(t,e){var r=h(((t=tP(t)).type="f",t)),n=3*Math.max(-8,Math.min(8,Math.floor(tA(e)/3))),o=Math.pow(10,-n),i=tN[8+n/3];return function(t){return r(o*t)+i}}}}({thousands:",",grouping:[3],currency:["$",""]})).format,a=o.formatPrefix;var tX=r(36967);function tG(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function tV(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function tK(t){return t<0?-t*t:t*t}function tQ(t){var e=t(tv,tv),r=1;return e.exponent=function(e){return arguments.length?1==(r=+e)?t(tv,tv):.5===r?t(tV,tK):t(tG(r),tG(1/r)):r},tI(e)}function tJ(){var t=tQ(tw());return t.copy=function(){return tx(t,tJ()).exponent(t.exponent())},tj.o.apply(t,arguments),t}function t0(){return tJ.apply(null,arguments).exponent(.5)}function t1(t){return Math.sign(t)*t*t}function t2(t,e){let r;if(void 0===e)for(let e of t)null!=e&&(r=e)&&(r=e);else{let n=-1;for(let o of t)null!=(o=e(o,++n,t))&&(r=o)&&(r=o)}return r}function t5(t,e){let r;if(void 0===e)for(let e of t)null!=e&&(r>e||void 0===r&&e>=e)&&(r=e);else{let n=-1;for(let o of t)null!=(o=e(o,++n,t))&&(r>o||void 0===r&&o>=o)&&(r=o)}return r}function t6(t,e){return(null==t||!(t>=t))-(null==e||!(e>=e))||(te?1:0)}function t3(t,e,r){let n=t[e];t[e]=t[r],t[r]=n}let t7=new Date,t4=new Date;function t8(t,e,r,n){function o(e){return t(e=0==arguments.length?new Date:new Date(+e)),e}return o.floor=e=>(t(e=new Date(+e)),e),o.ceil=r=>(t(r=new Date(r-1)),e(r,1),t(r),r),o.round=t=>{let e=o(t),r=o.ceil(t);return t-e(e(t=new Date(+t),null==r?1:Math.floor(r)),t),o.range=(r,n,i)=>{let a;let u=[];if(r=o.ceil(r),i=null==i?1:Math.floor(i),!(r0))return u;do u.push(a=new Date(+r)),e(r,i),t(r);while(at8(e=>{if(e>=e)for(;t(e),!r(e);)e.setTime(e-1)},(t,n)=>{if(t>=t){if(n<0)for(;++n<=0;)for(;e(t,-1),!r(t););else for(;--n>=0;)for(;e(t,1),!r(t););}}),r&&(o.count=(e,n)=>(t7.setTime(+e),t4.setTime(+n),t(t7),t(t4),Math.floor(r(t7,t4))),o.every=t=>isFinite(t=Math.floor(t))&&t>0?t>1?o.filter(n?e=>n(e)%t==0:e=>o.count(0,e)%t==0):o:null),o}let t9=t8(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);t9.every=t=>isFinite(t=Math.floor(t))&&t>0?t>1?t8(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):t9:null,t9.range;let et=t8(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+1e3*e)},(t,e)=>(e-t)/1e3,t=>t.getUTCSeconds());et.range;let ee=t8(t=>{t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds())},(t,e)=>{t.setTime(+t+6e4*e)},(t,e)=>(e-t)/6e4,t=>t.getMinutes());ee.range;let er=t8(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+6e4*e)},(t,e)=>(e-t)/6e4,t=>t.getUTCMinutes());er.range;let en=t8(t=>{t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds()-6e4*t.getMinutes())},(t,e)=>{t.setTime(+t+36e5*e)},(t,e)=>(e-t)/36e5,t=>t.getHours());en.range;let eo=t8(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+36e5*e)},(t,e)=>(e-t)/36e5,t=>t.getUTCHours());eo.range;let ei=t8(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/864e5,t=>t.getDate()-1);ei.range;let ea=t8(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>t.getUTCDate()-1);ea.range;let eu=t8(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>Math.floor(t/864e5));function ec(t){return t8(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(t,e)=>{t.setDate(t.getDate()+7*e)},(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/6048e5)}eu.range;let el=ec(0),es=ec(1),ef=ec(2),ep=ec(3),eh=ec(4),ed=ec(5),ey=ec(6);function ev(t){return t8(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+7*e)},(t,e)=>(e-t)/6048e5)}el.range,es.range,ef.range,ep.range,eh.range,ed.range,ey.range;let em=ev(0),eb=ev(1),eg=ev(2),ex=ev(3),ew=ev(4),eO=ev(5),ej=ev(6);em.range,eb.range,eg.range,ex.range,ew.range,eO.range,ej.range;let eS=t8(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth());eS.range;let eP=t8(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth());eP.range;let eE=t8(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());eE.every=t=>isFinite(t=Math.floor(t))&&t>0?t8(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)}):null,eE.range;let ek=t8(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());function eA(t,e,r,n,o,i){let a=[[et,1,1e3],[et,5,5e3],[et,15,15e3],[et,30,3e4],[i,1,6e4],[i,5,3e5],[i,15,9e5],[i,30,18e5],[o,1,36e5],[o,3,108e5],[o,6,216e5],[o,12,432e5],[n,1,864e5],[n,2,1728e5],[r,1,6048e5],[e,1,2592e6],[e,3,7776e6],[t,1,31536e6]];function u(e,r,n){let o=Math.abs(r-e)/n,i=w(([,,t])=>t).right(a,o);if(i===a.length)return t.every(b(e/31536e6,r/31536e6,n));if(0===i)return t9.every(Math.max(b(e,r,n),1));let[u,c]=a[o/a[i-1][2]isFinite(t=Math.floor(t))&&t>0?t8(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)}):null,ek.range;let[eM,e_]=eA(ek,eP,em,eu,eo,er),[eT,eC]=eA(eE,eS,el,ei,en,ee);function eN(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function eD(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function eI(t,e,r){return{y:t,m:e,d:r,H:0,M:0,S:0,L:0}}var eL={"-":"",_:" ",0:"0"},eB=/^\s*\d+/,eR=/^%/,ez=/[\\^$*+?|[\]().{}]/g;function eU(t,e,r){var n=t<0?"-":"",o=(n?-t:t)+"",i=o.length;return n+(i[t.toLowerCase(),e]))}function eZ(t,e,r){var n=eB.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function eW(t,e,r){var n=eB.exec(e.slice(r,r+1));return n?(t.u=+n[0],r+n[0].length):-1}function eY(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.U=+n[0],r+n[0].length):-1}function eH(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.V=+n[0],r+n[0].length):-1}function eX(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.W=+n[0],r+n[0].length):-1}function eG(t,e,r){var n=eB.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function eV(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function eK(t,e,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(r,r+6));return n?(t.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function eQ(t,e,r){var n=eB.exec(e.slice(r,r+1));return n?(t.q=3*n[0]-3,r+n[0].length):-1}function eJ(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function e0(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function e1(t,e,r){var n=eB.exec(e.slice(r,r+3));return n?(t.m=0,t.d=+n[0],r+n[0].length):-1}function e2(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function e5(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function e6(t,e,r){var n=eB.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function e3(t,e,r){var n=eB.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function e7(t,e,r){var n=eB.exec(e.slice(r,r+6));return n?(t.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function e4(t,e,r){var n=eR.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function e8(t,e,r){var n=eB.exec(e.slice(r));return n?(t.Q=+n[0],r+n[0].length):-1}function e9(t,e,r){var n=eB.exec(e.slice(r));return n?(t.s=+n[0],r+n[0].length):-1}function rt(t,e){return eU(t.getDate(),e,2)}function re(t,e){return eU(t.getHours(),e,2)}function rr(t,e){return eU(t.getHours()%12||12,e,2)}function rn(t,e){return eU(1+ei.count(eE(t),t),e,3)}function ro(t,e){return eU(t.getMilliseconds(),e,3)}function ri(t,e){return ro(t,e)+"000"}function ra(t,e){return eU(t.getMonth()+1,e,2)}function ru(t,e){return eU(t.getMinutes(),e,2)}function rc(t,e){return eU(t.getSeconds(),e,2)}function rl(t){var e=t.getDay();return 0===e?7:e}function rs(t,e){return eU(el.count(eE(t)-1,t),e,2)}function rf(t){var e=t.getDay();return e>=4||0===e?eh(t):eh.ceil(t)}function rp(t,e){return t=rf(t),eU(eh.count(eE(t),t)+(4===eE(t).getDay()),e,2)}function rh(t){return t.getDay()}function rd(t,e){return eU(es.count(eE(t)-1,t),e,2)}function ry(t,e){return eU(t.getFullYear()%100,e,2)}function rv(t,e){return eU((t=rf(t)).getFullYear()%100,e,2)}function rm(t,e){return eU(t.getFullYear()%1e4,e,4)}function rb(t,e){var r=t.getDay();return eU((t=r>=4||0===r?eh(t):eh.ceil(t)).getFullYear()%1e4,e,4)}function rg(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+eU(e/60|0,"0",2)+eU(e%60,"0",2)}function rx(t,e){return eU(t.getUTCDate(),e,2)}function rw(t,e){return eU(t.getUTCHours(),e,2)}function rO(t,e){return eU(t.getUTCHours()%12||12,e,2)}function rj(t,e){return eU(1+ea.count(ek(t),t),e,3)}function rS(t,e){return eU(t.getUTCMilliseconds(),e,3)}function rP(t,e){return rS(t,e)+"000"}function rE(t,e){return eU(t.getUTCMonth()+1,e,2)}function rk(t,e){return eU(t.getUTCMinutes(),e,2)}function rA(t,e){return eU(t.getUTCSeconds(),e,2)}function rM(t){var e=t.getUTCDay();return 0===e?7:e}function r_(t,e){return eU(em.count(ek(t)-1,t),e,2)}function rT(t){var e=t.getUTCDay();return e>=4||0===e?ew(t):ew.ceil(t)}function rC(t,e){return t=rT(t),eU(ew.count(ek(t),t)+(4===ek(t).getUTCDay()),e,2)}function rN(t){return t.getUTCDay()}function rD(t,e){return eU(eb.count(ek(t)-1,t),e,2)}function rI(t,e){return eU(t.getUTCFullYear()%100,e,2)}function rL(t,e){return eU((t=rT(t)).getUTCFullYear()%100,e,2)}function rB(t,e){return eU(t.getUTCFullYear()%1e4,e,4)}function rR(t,e){var r=t.getUTCDay();return eU((t=r>=4||0===r?ew(t):ew.ceil(t)).getUTCFullYear()%1e4,e,4)}function rz(){return"+0000"}function rU(){return"%"}function rF(t){return+t}function r$(t){return Math.floor(+t/1e3)}function rq(t){return new Date(t)}function rZ(t){return t instanceof Date?+t:+new Date(+t)}function rW(t,e,r,n,o,i,a,u,c,l){var s=tO(),f=s.invert,p=s.domain,h=l(".%L"),d=l(":%S"),y=l("%I:%M"),v=l("%I %p"),m=l("%a %d"),b=l("%b %d"),g=l("%B"),x=l("%Y");function w(t){return(c(t)1)for(var r,n,o,i=1,a=t[e[0]],u=a.length;i=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:rF,s:r$,S:rc,u:rl,U:rs,V:rp,w:rh,W:rd,x:null,X:null,y:ry,Y:rm,Z:rg,"%":rU},x={a:function(t){return a[t.getUTCDay()]},A:function(t){return i[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:rx,e:rx,f:rP,g:rL,G:rR,H:rw,I:rO,j:rj,L:rS,m:rE,M:rk,p:function(t){return o[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:rF,s:r$,S:rA,u:rM,U:r_,V:rC,w:rN,W:rD,x:null,X:null,y:rI,Y:rB,Z:rz,"%":rU},w={a:function(t,e,r){var n=h.exec(e.slice(r));return n?(t.w=d.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){var n=f.exec(e.slice(r));return n?(t.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){var n=m.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){var n=y.exec(e.slice(r));return n?(t.m=v.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,r,n){return S(t,e,r,n)},d:e0,e:e0,f:e7,g:eV,G:eG,H:e2,I:e2,j:e1,L:e3,m:eJ,M:e5,p:function(t,e,r){var n=l.exec(e.slice(r));return n?(t.p=s.get(n[0].toLowerCase()),r+n[0].length):-1},q:eQ,Q:e8,s:e9,S:e6,u:eW,U:eY,V:eH,w:eZ,W:eX,x:function(t,e,n){return S(t,r,e,n)},X:function(t,e,r){return S(t,n,e,r)},y:eV,Y:eG,Z:eK,"%":e4};function O(t,e){return function(r){var n,o,i,a=[],u=-1,c=0,l=t.length;for(r instanceof Date||(r=new Date(+r));++u53)return null;"w"in i||(i.w=1),"Z"in i?(n=(o=(n=eD(eI(i.y,0,1))).getUTCDay())>4||0===o?eb.ceil(n):eb(n),n=ea.offset(n,(i.V-1)*7),i.y=n.getUTCFullYear(),i.m=n.getUTCMonth(),i.d=n.getUTCDate()+(i.w+6)%7):(n=(o=(n=eN(eI(i.y,0,1))).getDay())>4||0===o?es.ceil(n):es(n),n=ei.offset(n,(i.V-1)*7),i.y=n.getFullYear(),i.m=n.getMonth(),i.d=n.getDate()+(i.w+6)%7)}else("W"in i||"U"in i)&&("w"in i||(i.w="u"in i?i.u%7:"W"in i?1:0),o="Z"in i?eD(eI(i.y,0,1)).getUTCDay():eN(eI(i.y,0,1)).getDay(),i.m=0,i.d="W"in i?(i.w+6)%7+7*i.W-(o+5)%7:i.w+7*i.U-(o+6)%7);return"Z"in i?(i.H+=i.Z/100|0,i.M+=i.Z%100,eD(i)):eN(i)}}function S(t,e,r,n){for(var o,i,a=0,u=e.length,c=r.length;a=c)return -1;if(37===(o=e.charCodeAt(a++))){if(!(i=w[(o=e.charAt(a++))in eL?e.charAt(a++):o])||(n=i(t,r,n))<0)return -1}else if(o!=r.charCodeAt(n++))return -1}return n}return g.x=O(r,g),g.X=O(n,g),g.c=O(e,g),x.x=O(r,x),x.X=O(n,x),x.c=O(e,x),{format:function(t){var e=O(t+="",g);return e.toString=function(){return t},e},parse:function(t){var e=j(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=O(t+="",x);return e.toString=function(){return t},e},utcParse:function(t){var e=j(t+="",!0);return e.toString=function(){return t},e}}}({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]})).format,u.parse,l=u.utcFormat,u.utcParse;var r2=r(22516),r5=r(76115);function r6(t){for(var e=t.length,r=Array(e);--e>=0;)r[e]=e;return r}function r3(t,e){return t[e]}function r7(t){let e=[];return e.key=t,e}var r4=r(95645),r8=r.n(r4),r9=r(99008),nt=r.n(r9),ne=r(77571),nr=r.n(ne),nn=r(86757),no=r.n(nn),ni=r(42715),na=r.n(ni),nu=r(13735),nc=r.n(nu),nl=r(11314),ns=r.n(nl),nf=r(82559),np=r.n(nf),nh=r(75551),nd=r.n(nh),ny=r(21652),nv=r.n(ny),nm=r(34935),nb=r.n(nm),ng=r(61134),nx=r.n(ng);function nw(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r=e?r.apply(void 0,o):t(e-a,nP(function(){for(var t=arguments.length,e=Array(t),n=0;nt.length)&&(e=t.length);for(var r=0,n=Array(e);rn&&(o=n,i=r),[o,i]}function nR(t,e,r){if(t.lte(0))return new(nx())(0);var n=nC.getDigitCount(t.toNumber()),o=new(nx())(10).pow(n),i=t.div(o),a=1!==n?.05:.1,u=new(nx())(Math.ceil(i.div(a).toNumber())).add(r).mul(a).mul(o);return e?u:new(nx())(Math.ceil(u))}function nz(t,e,r){var n=1,o=new(nx())(t);if(!o.isint()&&r){var i=Math.abs(t);i<1?(n=new(nx())(10).pow(nC.getDigitCount(t)-1),o=new(nx())(Math.floor(o.div(n).toNumber())).mul(n)):i>1&&(o=new(nx())(Math.floor(t)))}else 0===t?o=new(nx())(Math.floor((e-1)/2)):r||(o=new(nx())(Math.floor(t)));var a=Math.floor((e-1)/2);return nM(nA(function(t){return o.add(new(nx())(t-a).mul(n)).toNumber()}),nk)(0,e)}var nU=nT(function(t){var e=nD(t,2),r=e[0],n=e[1],o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6,i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],a=Math.max(o,2),u=nD(nB([r,n]),2),c=u[0],l=u[1];if(c===-1/0||l===1/0){var s=l===1/0?[c].concat(nN(nk(0,o-1).map(function(){return 1/0}))):[].concat(nN(nk(0,o-1).map(function(){return-1/0})),[l]);return r>n?n_(s):s}if(c===l)return nz(c,o,i);var f=function t(e,r,n,o){var i,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;if(!Number.isFinite((r-e)/(n-1)))return{step:new(nx())(0),tickMin:new(nx())(0),tickMax:new(nx())(0)};var u=nR(new(nx())(r).sub(e).div(n-1),o,a),c=Math.ceil((i=e<=0&&r>=0?new(nx())(0):(i=new(nx())(e).add(r).div(2)).sub(new(nx())(i).mod(u))).sub(e).div(u).toNumber()),l=Math.ceil(new(nx())(r).sub(i).div(u).toNumber()),s=c+l+1;return s>n?t(e,r,n,o,a+1):(s0?l+(n-s):l,c=r>0?c:c+(n-s)),{step:u,tickMin:i.sub(new(nx())(c).mul(u)),tickMax:i.add(new(nx())(l).mul(u))})}(c,l,a,i),p=f.step,h=f.tickMin,d=f.tickMax,y=nC.rangeStep(h,d.add(new(nx())(.1).mul(p)),p);return r>n?n_(y):y});nT(function(t){var e=nD(t,2),r=e[0],n=e[1],o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6,i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],a=Math.max(o,2),u=nD(nB([r,n]),2),c=u[0],l=u[1];if(c===-1/0||l===1/0)return[r,n];if(c===l)return nz(c,o,i);var s=nR(new(nx())(l).sub(c).div(a-1),i,0),f=nM(nA(function(t){return new(nx())(c).add(new(nx())(t).mul(s)).toNumber()}),nk)(0,a).filter(function(t){return t>=c&&t<=l});return r>n?n_(f):f});var nF=nT(function(t,e){var r=nD(t,2),n=r[0],o=r[1],i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],a=nD(nB([n,o]),2),u=a[0],c=a[1];if(u===-1/0||c===1/0)return[n,o];if(u===c)return[u];var l=nR(new(nx())(c).sub(u).div(Math.max(e,2)-1),i,0),s=[].concat(nN(nC.rangeStep(new(nx())(u),new(nx())(c).sub(new(nx())(.99).mul(l)),l)),[c]);return n>o?n_(s):s}),n$=r(13137),nq=r(16630),nZ=r(82944),nW=r(38569);function nY(t){return(nY="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function nH(t){return function(t){if(Array.isArray(t))return nX(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return nX(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return nX(t,void 0)}}(t)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function nX(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0,o=arguments.length>3?arguments[3]:void 0,i=-1,a=null!==(e=null==r?void 0:r.length)&&void 0!==e?e:0;if(a<=1)return 0;if(o&&"angleAxis"===o.axisType&&1e-6>=Math.abs(Math.abs(o.range[1]-o.range[0])-360))for(var u=o.range,c=0;c0?n[c-1].coordinate:n[a-1].coordinate,s=n[c].coordinate,f=c>=a-1?n[0].coordinate:n[c+1].coordinate,p=void 0;if((0,nq.uY)(s-l)!==(0,nq.uY)(f-s)){var h=[];if((0,nq.uY)(f-s)===(0,nq.uY)(u[1]-u[0])){p=f;var d=s+u[1]-u[0];h[0]=Math.min(d,(d+l)/2),h[1]=Math.max(d,(d+l)/2)}else{p=l;var y=f+u[1]-u[0];h[0]=Math.min(s,(y+s)/2),h[1]=Math.max(s,(y+s)/2)}var v=[Math.min(s,(p+s)/2),Math.max(s,(p+s)/2)];if(t>v[0]&&t<=v[1]||t>=h[0]&&t<=h[1]){i=n[c].index;break}}else{var m=Math.min(l,f),b=Math.max(l,f);if(t>(m+s)/2&&t<=(b+s)/2){i=n[c].index;break}}}else for(var g=0;g0&&g(r[g].coordinate+r[g-1].coordinate)/2&&t<=(r[g].coordinate+r[g+1].coordinate)/2||g===a-1&&t>(r[g].coordinate+r[g-1].coordinate)/2){i=r[g].index;break}return i},n1=function(t){var e,r,n=t.type.displayName,o=null!==(e=t.type)&&void 0!==e&&e.defaultProps?nV(nV({},t.type.defaultProps),t.props):t.props,i=o.stroke,a=o.fill;switch(n){case"Line":r=i;break;case"Area":case"Radar":r=i&&"none"!==i?i:a;break;default:r=a}return r},n2=function(t){var e=t.barSize,r=t.totalSize,n=t.stackGroups,o=void 0===n?{}:n;if(!o)return{};for(var i={},a=Object.keys(o),u=0,c=a.length;u=0});if(v&&v.length){var m=v[0].type.defaultProps,b=void 0!==m?nV(nV({},m),v[0].props):v[0].props,g=b.barSize,x=b[y];i[x]||(i[x]=[]);var w=nr()(g)?e:g;i[x].push({item:v[0],stackList:v.slice(1),barSize:nr()(w)?void 0:(0,nq.h1)(w,r,0)})}}return i},n5=function(t){var e,r=t.barGap,n=t.barCategoryGap,o=t.bandSize,i=t.sizeList,a=void 0===i?[]:i,u=t.maxBarSize,c=a.length;if(c<1)return null;var l=(0,nq.h1)(r,o,0,!0),s=[];if(a[0].barSize===+a[0].barSize){var f=!1,p=o/c,h=a.reduce(function(t,e){return t+e.barSize||0},0);(h+=(c-1)*l)>=o&&(h-=(c-1)*l,l=0),h>=o&&p>0&&(f=!0,p*=.9,h=c*p);var d={offset:((o-h)/2>>0)-l,size:0};e=a.reduce(function(t,e){var r={item:e.item,position:{offset:d.offset+d.size+l,size:f?p:e.barSize}},n=[].concat(nH(t),[r]);return d=n[n.length-1].position,e.stackList&&e.stackList.length&&e.stackList.forEach(function(t){n.push({item:t,position:d})}),n},s)}else{var y=(0,nq.h1)(n,o,0,!0);o-2*y-(c-1)*l<=0&&(l=0);var v=(o-2*y-(c-1)*l)/c;v>1&&(v>>=0);var m=u===+u?Math.min(v,u):v;e=a.reduce(function(t,e,r){var n=[].concat(nH(t),[{item:e.item,position:{offset:y+(v+l)*r+(v-m)/2,size:m}}]);return e.stackList&&e.stackList.length&&e.stackList.forEach(function(t){n.push({item:t,position:n[n.length-1].position})}),n},s)}return e},n6=function(t,e,r,n){var o=r.children,i=r.width,a=r.margin,u=i-(a.left||0)-(a.right||0),c=(0,nW.z)({children:o,legendWidth:u});if(c){var l=n||{},s=l.width,f=l.height,p=c.align,h=c.verticalAlign,d=c.layout;if(("vertical"===d||"horizontal"===d&&"middle"===h)&&"center"!==p&&(0,nq.hj)(t[p]))return nV(nV({},t),{},nK({},p,t[p]+(s||0)));if(("horizontal"===d||"vertical"===d&&"center"===p)&&"middle"!==h&&(0,nq.hj)(t[h]))return nV(nV({},t),{},nK({},h,t[h]+(f||0)))}return t},n3=function(t,e,r,n,o){var i=e.props.children,a=(0,nZ.NN)(i,n$.W).filter(function(t){var e;return e=t.props.direction,!!nr()(o)||("horizontal"===n?"yAxis"===o:"vertical"===n||"x"===e?"xAxis"===o:"y"!==e||"yAxis"===o)});if(a&&a.length){var u=a.map(function(t){return t.props.dataKey});return t.reduce(function(t,e){var n=nQ(e,r);if(nr()(n))return t;var o=Array.isArray(n)?[nt()(n),r8()(n)]:[n,n],i=u.reduce(function(t,r){var n=nQ(e,r,0),i=o[0]-Math.abs(Array.isArray(n)?n[0]:n),a=o[1]+Math.abs(Array.isArray(n)?n[1]:n);return[Math.min(i,t[0]),Math.max(a,t[1])]},[1/0,-1/0]);return[Math.min(i[0],t[0]),Math.max(i[1],t[1])]},[1/0,-1/0])}return null},n7=function(t,e,r,n,o){var i=e.map(function(e){return n3(t,e,r,o,n)}).filter(function(t){return!nr()(t)});return i&&i.length?i.reduce(function(t,e){return[Math.min(t[0],e[0]),Math.max(t[1],e[1])]},[1/0,-1/0]):null},n4=function(t,e,r,n,o){var i=e.map(function(e){var i=e.props.dataKey;return"number"===r&&i&&n3(t,e,i,n)||nJ(t,i,r,o)});if("number"===r)return i.reduce(function(t,e){return[Math.min(t[0],e[0]),Math.max(t[1],e[1])]},[1/0,-1/0]);var a={};return i.reduce(function(t,e){for(var r=0,n=e.length;r=2?2*(0,nq.uY)(a[0]-a[1])*c:c,e&&(t.ticks||t.niceTicks))?(t.ticks||t.niceTicks).map(function(t){return{coordinate:n(o?o.indexOf(t):t)+c,value:t,offset:c}}).filter(function(t){return!np()(t.coordinate)}):t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(t,e){return{coordinate:n(t)+c,value:t,index:e,offset:c}}):n.ticks&&!r?n.ticks(t.tickCount).map(function(t){return{coordinate:n(t)+c,value:t,offset:c}}):n.domain().map(function(t,e){return{coordinate:n(t)+c,value:o?o[t]:t,index:e,offset:c}})},oe=new WeakMap,or=function(t,e){if("function"!=typeof e)return t;oe.has(t)||oe.set(t,new WeakMap);var r=oe.get(t);if(r.has(e))return r.get(e);var n=function(){t.apply(void 0,arguments),e.apply(void 0,arguments)};return r.set(e,n),n},on=function(t,e,r){var n=t.scale,o=t.type,i=t.layout,a=t.axisType;if("auto"===n)return"radial"===i&&"radiusAxis"===a?{scale:f.Z(),realScaleType:"band"}:"radial"===i&&"angleAxis"===a?{scale:tL(),realScaleType:"linear"}:"category"===o&&e&&(e.indexOf("LineChart")>=0||e.indexOf("AreaChart")>=0||e.indexOf("ComposedChart")>=0&&!r)?{scale:f.x(),realScaleType:"point"}:"category"===o?{scale:f.Z(),realScaleType:"band"}:{scale:tL(),realScaleType:"linear"};if(na()(n)){var u="scale".concat(nd()(n));return{scale:(s[u]||f.x)(),realScaleType:s[u]?u:"point"}}return no()(n)?{scale:n}:{scale:f.x(),realScaleType:"point"}},oo=function(t){var e=t.domain();if(e&&!(e.length<=2)){var r=e.length,n=t.range(),o=Math.min(n[0],n[1])-1e-4,i=Math.max(n[0],n[1])+1e-4,a=t(e[0]),u=t(e[r-1]);(ai||ui)&&t.domain([e[0],e[r-1]])}},oi=function(t,e){if(!t)return null;for(var r=0,n=t.length;rn)&&(o[1]=n),o[0]>n&&(o[0]=n),o[1]=0?(t[a][r][0]=o,t[a][r][1]=o+u,o=t[a][r][1]):(t[a][r][0]=i,t[a][r][1]=i+u,i=t[a][r][1])}},expand:function(t,e){if((n=t.length)>0){for(var r,n,o,i=0,a=t[0].length;i0){for(var r,n=0,o=t[e[0]],i=o.length;n0&&(n=(r=t[e[0]]).length)>0){for(var r,n,o,i=0,a=1;a=0?(t[i][r][0]=o,t[i][r][1]=o+a,o=t[i][r][1]):(t[i][r][0]=0,t[i][r][1]=0)}}},oc=function(t,e,r){var n=e.map(function(t){return t.props.dataKey}),o=ou[r];return(function(){var t=(0,r5.Z)([]),e=r6,r=r1,n=r3;function o(o){var i,a,u=Array.from(t.apply(this,arguments),r7),c=u.length,l=-1;for(let t of o)for(i=0,++l;i=0?0:o<0?o:n}return r[0]},od=function(t,e){var r,n=(null!==(r=t.type)&&void 0!==r&&r.defaultProps?nV(nV({},t.type.defaultProps),t.props):t.props).stackId;if((0,nq.P2)(n)){var o=e[n];if(o){var i=o.items.indexOf(t);return i>=0?o.stackedData[i]:null}}return null},oy=function(t,e,r){return Object.keys(t).reduce(function(n,o){var i=t[o].stackedData.reduce(function(t,n){var o=n.slice(e,r+1).reduce(function(t,e){return[nt()(e.concat([t[0]]).filter(nq.hj)),r8()(e.concat([t[1]]).filter(nq.hj))]},[1/0,-1/0]);return[Math.min(t[0],o[0]),Math.max(t[1],o[1])]},[1/0,-1/0]);return[Math.min(i[0],n[0]),Math.max(i[1],n[1])]},[1/0,-1/0]).map(function(t){return t===1/0||t===-1/0?0:t})},ov=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,om=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,ob=function(t,e,r){if(no()(t))return t(e,r);if(!Array.isArray(t))return e;var n=[];if((0,nq.hj)(t[0]))n[0]=r?t[0]:Math.min(t[0],e[0]);else if(ov.test(t[0])){var o=+ov.exec(t[0])[1];n[0]=e[0]-o}else no()(t[0])?n[0]=t[0](e[0]):n[0]=e[0];if((0,nq.hj)(t[1]))n[1]=r?t[1]:Math.max(t[1],e[1]);else if(om.test(t[1])){var i=+om.exec(t[1])[1];n[1]=e[1]+i}else no()(t[1])?n[1]=t[1](e[1]):n[1]=e[1];return n},og=function(t,e,r){if(t&&t.scale&&t.scale.bandwidth){var n=t.scale.bandwidth();if(!r||n>0)return n}if(t&&e&&e.length>=2){for(var o=nb()(e,function(t){return t.coordinate}),i=1/0,a=1,u=o.length;a1&&void 0!==arguments[1]?arguments[1]:{};if(null==t||n.x.isSsr)return{width:0,height:0};var o=(Object.keys(e=a({},r)).forEach(function(t){e[t]||delete e[t]}),e),i=JSON.stringify({text:t,copyStyle:o});if(u.widthCache[i])return u.widthCache[i];try{var s=document.getElementById(l);s||((s=document.createElement("span")).setAttribute("id",l),s.setAttribute("aria-hidden","true"),document.body.appendChild(s));var f=a(a({},c),o);Object.assign(s.style,f),s.textContent="".concat(t);var p=s.getBoundingClientRect(),h={width:p.width,height:p.height};return u.widthCache[i]=h,++u.cacheCount>2e3&&(u.cacheCount=0,u.widthCache={}),h}catch(t){return{width:0,height:0}}},f=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}}},16630:function(t,e,r){"use strict";r.d(e,{Ap:function(){return S},EL:function(){return g},Kt:function(){return w},P2:function(){return m},Rw:function(){return v},bv:function(){return O},fC:function(){return P},h1:function(){return x},hU:function(){return d},hj:function(){return y},k4:function(){return j},uY:function(){return h}});var n=r(42715),o=r.n(n),i=r(82559),a=r.n(i),u=r(13735),c=r.n(u),l=r(22345),s=r.n(l),f=r(77571),p=r.n(f),h=function(t){return 0===t?0:t>0?1:-1},d=function(t){return o()(t)&&t.indexOf("%")===t.length-1},y=function(t){return s()(t)&&!a()(t)},v=function(t){return p()(t)},m=function(t){return y(t)||o()(t)},b=0,g=function(t){var e=++b;return"".concat(t||"").concat(e)},x=function(t,e){var r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!y(t)&&!o()(t))return n;if(d(t)){var u=t.indexOf("%");r=e*parseFloat(t.slice(0,u))/100}else r=+t;return a()(r)&&(r=n),i&&r>e&&(r=e),r},w=function(t){if(!t)return null;var e=Object.keys(t);return e&&e.length?t[e[0]]:null},O=function(t){if(!Array.isArray(t))return!1;for(var e=t.length,r={},n=0;n2?r-2:0),o=2;ot.length)&&(e=t.length);for(var r=0,n=Array(e);r2&&void 0!==arguments[2]?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(r.left||0)-(r.right||0)),Math.abs(e-(r.top||0)-(r.bottom||0)))/2},b=function(t,e,r,n,i){var a=t.width,u=t.height,s=t.startAngle,f=t.endAngle,y=(0,c.h1)(t.cx,a,a/2),v=(0,c.h1)(t.cy,u,u/2),b=m(a,u,r),g=(0,c.h1)(t.innerRadius,b,0),x=(0,c.h1)(t.outerRadius,b,.8*b);return Object.keys(e).reduce(function(t,r){var a,u=e[r],c=u.domain,m=u.reversed;if(o()(u.range))"angleAxis"===n?a=[s,f]:"radiusAxis"===n&&(a=[g,x]),m&&(a=[a[1],a[0]]);else{var b,w=function(t){if(Array.isArray(t))return t}(b=a=u.range)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,u=[],c=!0,l=!1;try{for(i=(r=r.call(t)).next;!(c=(n=i.call(r)).done)&&(u.push(n.value),2!==u.length);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return u}}(b,2)||function(t,e){if(t){if("string"==typeof t)return d(t,2);var r=Object.prototype.toString.call(t).slice(8,-1);if("Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return d(t,2)}}(b,2)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}();s=w[0],f=w[1]}var O=(0,l.Hq)(u,i),j=O.realScaleType,S=O.scale;S.domain(c).range(a),(0,l.zF)(S);var P=(0,l.g$)(S,p(p({},u),{},{realScaleType:j})),E=p(p(p({},u),P),{},{range:a,radius:x,realScaleType:j,scale:S,cx:y,cy:v,innerRadius:g,outerRadius:x,startAngle:s,endAngle:f});return p(p({},t),{},h({},r,E))},{})},g=function(t,e){var r=t.x,n=t.y;return Math.sqrt(Math.pow(r-e.x,2)+Math.pow(n-e.y,2))},x=function(t,e){var r=t.x,n=t.y,o=e.cx,i=e.cy,a=g({x:r,y:n},{x:o,y:i});if(a<=0)return{radius:a};var u=Math.acos((r-o)/a);return n>i&&(u=2*Math.PI-u),{radius:a,angle:180*u/Math.PI,angleInRadian:u}},w=function(t){var e=t.startAngle,r=t.endAngle,n=Math.min(Math.floor(e/360),Math.floor(r/360));return{startAngle:e-360*n,endAngle:r-360*n}},O=function(t,e){var r,n=x({x:t.x,y:t.y},e),o=n.radius,i=n.angle,a=e.innerRadius,u=e.outerRadius;if(ou)return!1;if(0===o)return!0;var c=w(e),l=c.startAngle,s=c.endAngle,f=i;if(l<=s){for(;f>s;)f-=360;for(;f=l&&f<=s}else{for(;f>l;)f-=360;for(;f=s&&f<=l}return r?p(p({},e),{},{radius:o,angle:f+360*Math.min(Math.floor(e.startAngle/360),Math.floor(e.endAngle/360))}):null},j=function(t){return(0,i.isValidElement)(t)||u()(t)||"boolean"==typeof t?"":t.className}},82944:function(t,e,r){"use strict";r.d(e,{$R:function(){return R},Bh:function(){return B},Gf:function(){return j},L6:function(){return N},NN:function(){return k},TT:function(){return M},eu:function(){return L},jf:function(){return T},rL:function(){return D},sP:function(){return A}});var n=r(13735),o=r.n(n),i=r(77571),a=r.n(i),u=r(42715),c=r.n(u),l=r(86757),s=r.n(l),f=r(28302),p=r.n(f),h=r(2265),d=r(14326),y=r(16630),v=r(46485),m=r(41637),b=["children"],g=["children"];function x(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function w(t){return(w="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var O={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},j=function(t){return"string"==typeof t?t:t?t.displayName||t.name||"Component":""},S=null,P=null,E=function t(e){if(e===S&&Array.isArray(P))return P;var r=[];return h.Children.forEach(e,function(e){a()(e)||((0,d.isFragment)(e)?r=r.concat(t(e.props.children)):r.push(e))}),P=r,S=e,r};function k(t,e){var r=[],n=[];return n=Array.isArray(e)?e.map(function(t){return j(t)}):[j(e)],E(t).forEach(function(t){var e=o()(t,"type.displayName")||o()(t,"type.name");-1!==n.indexOf(e)&&r.push(t)}),r}function A(t,e){var r=k(t,e);return r&&r[0]}var M=function(t){if(!t||!t.props)return!1;var e=t.props,r=e.width,n=e.height;return!!(0,y.hj)(r)&&!(r<=0)&&!!(0,y.hj)(n)&&!(n<=0)},_=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],T=function(t){return t&&"object"===w(t)&&"clipDot"in t},C=function(t,e,r,n){var o,i=null!==(o=null===m.ry||void 0===m.ry?void 0:m.ry[n])&&void 0!==o?o:[];return e.startsWith("data-")||!s()(t)&&(n&&i.includes(e)||m.Yh.includes(e))||r&&m.nv.includes(e)},N=function(t,e,r){if(!t||"function"==typeof t||"boolean"==typeof t)return null;var n=t;if((0,h.isValidElement)(t)&&(n=t.props),!p()(n))return null;var o={};return Object.keys(n).forEach(function(t){var i;C(null===(i=n)||void 0===i?void 0:i[t],t,e,r)&&(o[t]=n[t])}),o},D=function t(e,r){if(e===r)return!0;var n=h.Children.count(e);if(n!==h.Children.count(r))return!1;if(0===n)return!0;if(1===n)return I(Array.isArray(e)?e[0]:e,Array.isArray(r)?r[0]:r);for(var o=0;o=0)r.push(t);else if(t){var i=j(t.type),a=e[i]||{},u=a.handler,l=a.once;if(u&&(!l||!n[i])){var s=u(t,i,o);r.push(s),n[i]=!0}}}),r},B=function(t){var e=t&&t.type;return e&&O[e]?O[e]:null},R=function(t,e){return E(e).indexOf(t)}},46485:function(t,e,r){"use strict";function n(t,e){for(var r in t)if(({}).hasOwnProperty.call(t,r)&&(!({}).hasOwnProperty.call(e,r)||t[r]!==e[r]))return!1;for(var n in e)if(({}).hasOwnProperty.call(e,n)&&!({}).hasOwnProperty.call(t,n))return!1;return!0}r.d(e,{w:function(){return n}})},38569:function(t,e,r){"use strict";r.d(e,{z:function(){return l}});var n=r(22190),o=r(85355),i=r(82944);function a(t){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function u(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function c(t){for(var e=1;e=0))throw Error(`invalid digits: ${t}`);if(e>15)return a;let r=10**e;return function(t){this._+=t[0];for(let e=1,n=t.length;e1e-6){if(Math.abs(f*c-l*s)>1e-6&&i){let h=r-a,d=o-u,y=c*c+l*l,v=Math.sqrt(y),m=Math.sqrt(p),b=i*Math.tan((n-Math.acos((y+p-(h*h+d*d))/(2*v*m)))/2),g=b/m,x=b/v;Math.abs(g-1)>1e-6&&this._append`L${t+g*s},${e+g*f}`,this._append`A${i},${i},0,0,${+(f*h>s*d)},${this._x1=t+x*c},${this._y1=e+x*l}`}else this._append`L${this._x1=t},${this._y1=e}`}}arc(t,e,r,a,u,c){if(t=+t,e=+e,c=!!c,(r=+r)<0)throw Error(`negative radius: ${r}`);let l=r*Math.cos(a),s=r*Math.sin(a),f=t+l,p=e+s,h=1^c,d=c?a-u:u-a;null===this._x1?this._append`M${f},${p}`:(Math.abs(this._x1-f)>1e-6||Math.abs(this._y1-p)>1e-6)&&this._append`L${f},${p}`,r&&(d<0&&(d=d%o+o),d>i?this._append`A${r},${r},0,1,${h},${t-l},${e-s}A${r},${r},0,1,${h},${this._x1=f},${this._y1=p}`:d>1e-6&&this._append`A${r},${r},0,${+(d>=n)},${h},${this._x1=t+r*Math.cos(u)},${this._y1=e+r*Math.sin(u)}`)}rect(t,e,r,n){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}h${r=+r}v${+n}h${-r}Z`}toString(){return this._}}function c(t){let e=3;return t.digits=function(r){if(!arguments.length)return e;if(null==r)e=null;else{let t=Math.floor(r);if(!(t>=0))throw RangeError(`invalid digits: ${r}`);e=t}return t},()=>new u(e)}u.prototype},59121:function(t,e,r){"use strict";r.d(e,{E:function(){return i}});var n=r(99649),o=r(63497);function i(t,e){let r=(0,n.Q)(t);return isNaN(e)?(0,o.L)(t,NaN):(e&&r.setDate(r.getDate()+e),r)}},31091:function(t,e,r){"use strict";r.d(e,{z:function(){return i}});var n=r(99649),o=r(63497);function i(t,e){let r=(0,n.Q)(t);if(isNaN(e))return(0,o.L)(t,NaN);if(!e)return r;let i=r.getDate(),a=(0,o.L)(t,r.getTime());return(a.setMonth(r.getMonth()+e+1,0),i>=a.getDate())?a:(r.setFullYear(a.getFullYear(),a.getMonth(),i),r)}},63497:function(t,e,r){"use strict";function n(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}r.d(e,{L:function(){return n}})},99649:function(t,e,r){"use strict";function n(t){let e=Object.prototype.toString.call(t);return t instanceof Date||"object"==typeof t&&"[object Date]"===e?new t.constructor(+t):new Date("number"==typeof t||"[object Number]"===e||"string"==typeof t||"[object String]"===e?t:NaN)}r.d(e,{Q:function(){return n}})},69398:function(t,e,r){"use strict";function n(t,e){if(!t)throw Error("Invariant failed")}r.d(e,{Z:function(){return n}})}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1112-0b9bd4ebde18e77b.js b/litellm/proxy/_experimental/out/_next/static/chunks/1112-0b9bd4ebde18e77b.js deleted file mode 100644 index ea4e968a055..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/1112-0b9bd4ebde18e77b.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1112],{41112:function(e,l,s){s.d(l,{Z:function(){return B}});var a=s(57437),t=s(2265),r=s(16312),i=s(22116),n=s(19250),o=s(4260),c=s(37592),d=s(10032),m=s(42264),x=s(43769);let{TextArea:u}=o.default,{Option:h}=c.default,g=["Development","Productivity","Learning","Security","Data & Analytics","Integration","Testing","Documentation"];var p=e=>{let{visible:l,onClose:s,accessToken:p,onSuccess:j}=e,[y]=d.Z.useForm(),[b,N]=(0,t.useState)(!1),[Z,f]=(0,t.useState)("github"),v=async e=>{if(!p){m.ZP.error("No access token available");return}if(!(0,x.$L)(e.name)){m.ZP.error("Plugin name must be kebab-case (lowercase letters, numbers, and hyphens only)");return}if(e.version&&!(0,x.Nq)(e.version)){m.ZP.error("Version must be in semantic versioning format (e.g., 1.0.0)");return}if(e.authorEmail&&!(0,x.vV)(e.authorEmail)){m.ZP.error("Invalid email format");return}if(e.homepage&&!(0,x.jv)(e.homepage)){m.ZP.error("Invalid homepage URL format");return}N(!0);try{let l={name:e.name.trim(),source:"github"===Z?{source:"github",repo:e.repo.trim()}:{source:"url",url:e.url.trim()}};e.version&&(l.version=e.version.trim()),e.description&&(l.description=e.description.trim()),(e.authorName||e.authorEmail)&&(l.author={},e.authorName&&(l.author.name=e.authorName.trim()),e.authorEmail&&(l.author.email=e.authorEmail.trim())),e.homepage&&(l.homepage=e.homepage.trim()),e.category&&(l.category=e.category),e.keywords&&(l.keywords=(0,x.jE)(e.keywords)),await (0,n.registerClaudeCodePlugin)(p,l),m.ZP.success("Plugin registered successfully"),y.resetFields(),f("github"),j(),s()}catch(e){console.error("Error registering plugin:",e),m.ZP.error("Failed to register plugin")}finally{N(!1)}},C=()=>{y.resetFields(),f("github"),s()};return(0,a.jsx)(i.Z,{title:"Add New Claude Code Plugin",open:l,onCancel:C,footer:null,width:700,className:"top-8",children:(0,a.jsxs)(d.Z,{form:y,layout:"vertical",onFinish:v,className:"mt-4",children:[(0,a.jsx)(d.Z.Item,{label:"Plugin Name",name:"name",rules:[{required:!0,message:"Please enter plugin name"},{pattern:/^[a-z0-9-]+$/,message:"Name must be kebab-case (lowercase, numbers, hyphens only)"}],tooltip:"Unique identifier in kebab-case format (e.g., my-awesome-plugin)",children:(0,a.jsx)(o.default,{placeholder:"my-awesome-plugin",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Source Type",name:"sourceType",initialValue:"github",rules:[{required:!0,message:"Please select source type"}],children:(0,a.jsxs)(c.default,{onChange:e=>{f(e),y.setFieldsValue({repo:void 0,url:void 0})},className:"rounded-lg",children:[(0,a.jsx)(h,{value:"github",children:"GitHub"}),(0,a.jsx)(h,{value:"url",children:"URL"})]})}),"github"===Z&&(0,a.jsx)(d.Z.Item,{label:"GitHub Repository",name:"repo",rules:[{required:!0,message:"Please enter repository"},{pattern:/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/,message:"Repository must be in format: org/repo"}],tooltip:"Format: organization/repository (e.g., anthropics/claude-code)",children:(0,a.jsx)(o.default,{placeholder:"anthropics/claude-code",className:"rounded-lg"})}),"url"===Z&&(0,a.jsx)(d.Z.Item,{label:"Git URL",name:"url",rules:[{required:!0,message:"Please enter git URL"}],tooltip:"Full git URL to the repository",children:(0,a.jsx)(o.default,{type:"url",placeholder:"https://github.com/org/repo.git",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Version (Optional)",name:"version",tooltip:"Semantic version (e.g., 1.0.0)",children:(0,a.jsx)(o.default,{placeholder:"1.0.0",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Description (Optional)",name:"description",tooltip:"Brief description of what the plugin does",children:(0,a.jsx)(u,{rows:3,placeholder:"A plugin that helps with...",maxLength:500,className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Category (Optional)",name:"category",tooltip:"Select a category or enter a custom one",children:(0,a.jsx)(c.default,{placeholder:"Select or type a category",allowClear:!0,showSearch:!0,optionFilterProp:"children",className:"rounded-lg",children:g.map(e=>(0,a.jsx)(h,{value:e,children:e},e))})}),(0,a.jsx)(d.Z.Item,{label:"Keywords (Optional)",name:"keywords",tooltip:"Comma-separated list of keywords for search",children:(0,a.jsx)(o.default,{placeholder:"search, web, api",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Author Name (Optional)",name:"authorName",tooltip:"Name of the plugin author or organization",children:(0,a.jsx)(o.default,{placeholder:"Your Name or Organization",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Author Email (Optional)",name:"authorEmail",rules:[{type:"email",message:"Please enter a valid email"}],tooltip:"Contact email for the plugin author",children:(0,a.jsx)(o.default,{type:"email",placeholder:"author@example.com",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Homepage (Optional)",name:"homepage",rules:[{type:"url",message:"Please enter a valid URL"}],tooltip:"URL to the plugin's homepage or documentation",children:(0,a.jsx)(o.default,{type:"url",placeholder:"https://example.com",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{className:"mb-0 mt-6",children:(0,a.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,a.jsx)(r.z,{variant:"secondary",onClick:C,disabled:b,children:"Cancel"}),(0,a.jsx)(r.z,{type:"submit",loading:b,children:b?"Registering...":"Register Plugin"})]})})]})})},j=s(23639),y=s(74998),b=s(44633),N=s(86462),Z=s(49084),f=s(71594),v=s(24525),C=s(41649),w=s(78489),P=s(21626),k=s(97214),S=s(28241),_=s(58834),z=s(69552),I=s(71876),E=s(99981),A=s(63709),D=s(9114),L=e=>{let{pluginsList:l,isLoading:s,onDeleteClick:r,accessToken:i,onPluginUpdated:o,isAdmin:c,onPluginClick:d}=e,[m,u]=(0,t.useState)([{id:"created_at",desc:!0}]),[h,g]=(0,t.useState)(null),p=e=>e?new Date(e).toLocaleString():"-",L=e=>{navigator.clipboard.writeText(e),D.Z.success("Copied to clipboard!")},R=async e=>{if(i){g(e.id);try{e.enabled?(await (0,n.disableClaudeCodePlugin)(i,e.name),D.Z.success('Plugin "'.concat(e.name,'" disabled'))):(await (0,n.enableClaudeCodePlugin)(i,e.name),D.Z.success('Plugin "'.concat(e.name,'" enabled'))),o()}catch(e){D.Z.error("Failed to toggle plugin status")}finally{g(null)}}},F=[{header:"Plugin Name",accessorKey:"name",cell:e=>{let{row:l}=e,s=l.original,t=s.name||"";return(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(E.Z,{title:t,children:(0,a.jsx)(w.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 min-w-[150px] justify-start",onClick:()=>d(s.id),children:t})}),(0,a.jsx)(E.Z,{title:"Copy Plugin ID",children:(0,a.jsx)(j.Z,{onClick:e=>{e.stopPropagation(),L(s.id)},className:"cursor-pointer text-gray-500 hover:text-blue-500 text-xs"})})]})}},{header:"Version",accessorKey:"version",cell:e=>{let{row:l}=e,s=l.original.version||"N/A";return(0,a.jsx)("span",{className:"text-xs text-gray-600",children:s})}},{header:"Description",accessorKey:"description",cell:e=>{let{row:l}=e,s=l.original.description||"No description";return(0,a.jsx)(E.Z,{title:s,children:(0,a.jsx)("span",{className:"text-xs text-gray-600 block max-w-[300px] truncate",children:s})})}},{header:"Category",accessorKey:"category",cell:e=>{let{row:l}=e,s=l.original.category;if(!s)return(0,a.jsx)(C.Z,{color:"gray",className:"text-xs font-normal",size:"xs",children:"Uncategorized"});let t=(0,x.LH)(s);return(0,a.jsx)(C.Z,{color:t,className:"text-xs font-normal",size:"xs",children:s})}},{header:"Enabled",accessorKey:"enabled",cell:e=>{let{row:l}=e,s=l.original;return(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(C.Z,{color:s.enabled?"green":"gray",className:"text-xs font-normal",size:"xs",children:s.enabled?"Yes":"No"}),c&&(0,a.jsx)(E.Z,{title:s.enabled?"Disable plugin":"Enable plugin",children:(0,a.jsx)(A.Z,{size:"small",checked:s.enabled,loading:h===s.id,onChange:()=>R(s)})})]})}},{header:"Created At",accessorKey:"created_at",cell:e=>{let{row:l}=e,s=l.original;return(0,a.jsx)(E.Z,{title:s.created_at,children:(0,a.jsx)("span",{className:"text-xs",children:p(s.created_at)})})}},...c?[{header:"Actions",id:"actions",enableSorting:!1,cell:e=>{let{row:l}=e,s=l.original;return(0,a.jsx)("div",{className:"flex items-center gap-1",children:(0,a.jsx)(E.Z,{title:"Delete plugin",children:(0,a.jsx)(w.Z,{size:"xs",variant:"light",color:"red",onClick:e=>{e.stopPropagation(),r(s.name,s.name)},icon:y.Z,className:"text-red-500 hover:text-red-700 hover:bg-red-50"})})})}}]:[]],U=(0,f.b7)({data:l,columns:F,state:{sorting:m},onSortingChange:u,getCoreRowModel:(0,v.sC)(),getSortedRowModel:(0,v.tj)(),enableSorting:!0});return(0,a.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,a.jsx)("div",{className:"overflow-x-auto",children:(0,a.jsxs)(P.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,a.jsx)(_.Z,{children:U.getHeaderGroups().map(e=>(0,a.jsx)(I.Z,{children:e.headers.map(e=>(0,a.jsx)(z.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.getCanSort()?e.column.getToggleSortingHandler():void 0,children:(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,f.ie)(e.column.columnDef.header,e.getContext())}),e.column.getCanSort()&&(0,a.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,a.jsx)(b.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,a.jsx)(N.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,a.jsx)(Z.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,a.jsx)(k.Z,{children:s?(0,a.jsx)(I.Z,{children:(0,a.jsx)(S.Z,{colSpan:F.length,className:"h-8 text-center",children:(0,a.jsx)("div",{className:"text-center text-gray-500",children:(0,a.jsx)("p",{children:"Loading..."})})})}):l&&l.length>0?U.getRowModel().rows.map(e=>(0,a.jsx)(I.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,a.jsx)(S.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,f.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,a.jsx)(I.Z,{children:(0,a.jsx)(S.Z,{colSpan:F.length,className:"h-8 text-center",children:(0,a.jsx)("div",{className:"text-center text-gray-500",children:(0,a.jsx)("p",{children:"No plugins found. Add one to get started."})})})})})]})})})},R=s(20347),F=s(10900),U=s(3477),O=s(12514),T=s(67101),H=s(84264),K=s(96761),V=s(10353),q=e=>{let{pluginId:l,onClose:s,accessToken:r,isAdmin:i,onPluginUpdated:o}=e,[c,d]=(0,t.useState)(null),[m,u]=(0,t.useState)(!0),[h,g]=(0,t.useState)(!1);(0,t.useEffect)(()=>{p()},[l,r]);let p=async()=>{if(r){u(!0);try{let e=await (0,n.getClaudeCodePluginDetails)(r,l);d(e.plugin)}catch(e){console.error("Error fetching plugin info:",e),D.Z.error("Failed to load plugin information")}finally{u(!1)}}},y=async()=>{if(r&&c){g(!0);try{c.enabled?(await (0,n.disableClaudeCodePlugin)(r,c.name),D.Z.success('Plugin "'.concat(c.name,'" disabled'))):(await (0,n.enableClaudeCodePlugin)(r,c.name),D.Z.success('Plugin "'.concat(c.name,'" enabled'))),o(),p()}catch(e){D.Z.error("Failed to toggle plugin status")}finally{g(!1)}}},b=e=>{navigator.clipboard.writeText(e),D.Z.success("Copied to clipboard!")};if(m)return(0,a.jsx)("div",{className:"flex items-center justify-center p-8",children:(0,a.jsx)(V.Z,{size:"large"})});if(!c)return(0,a.jsxs)("div",{className:"p-8 text-center text-gray-500",children:[(0,a.jsx)("p",{children:"Plugin not found"}),(0,a.jsx)(w.Z,{className:"mt-4",onClick:s,children:"Go Back"})]});let N=(0,x.aB)(c),Z=(0,x.OB)(c.source),f=(0,x.LH)(c.category);return(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsxs)("div",{className:"flex items-center gap-3 mb-6",children:[(0,a.jsx)(F.Z,{className:"h-5 w-5 cursor-pointer text-gray-500 hover:text-gray-700",onClick:s}),(0,a.jsx)("h2",{className:"text-2xl font-bold",children:c.name}),c.version&&(0,a.jsxs)(C.Z,{color:"blue",size:"xs",children:["v",c.version]}),c.category&&(0,a.jsx)(C.Z,{color:f,size:"xs",children:c.category}),(0,a.jsx)(C.Z,{color:c.enabled?"green":"gray",size:"xs",children:c.enabled?"Enabled":"Disabled"})]}),(0,a.jsx)(O.Z,{children:(0,a.jsxs)("div",{className:"flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"flex-1",children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs mb-2",children:"Install Command"}),(0,a.jsx)("div",{className:"font-mono bg-gray-100 px-3 py-2 rounded text-sm",children:N})]}),(0,a.jsx)(E.Z,{title:"Copy install command",children:(0,a.jsx)(w.Z,{size:"xs",variant:"secondary",icon:j.Z,onClick:()=>b(N),className:"ml-4",children:"Copy"})})]})}),(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Plugin Details"}),(0,a.jsxs)(T.Z,{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 mt-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Plugin ID"}),(0,a.jsxs)("div",{className:"flex items-center gap-2 mt-1",children:[(0,a.jsx)(H.Z,{className:"font-mono text-xs",children:c.id}),(0,a.jsx)(j.Z,{className:"cursor-pointer text-gray-500 hover:text-blue-500 text-xs",onClick:()=>b(c.id)})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Name"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:c.name})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Version"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:c.version||"N/A"})]}),(0,a.jsxs)("div",{className:"col-span-2",children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Source"}),(0,a.jsxs)("div",{className:"flex items-center gap-2 mt-1",children:[(0,a.jsx)(H.Z,{className:"font-semibold",children:(0,x.i5)(c.source)}),Z&&(0,a.jsx)("a",{href:Z,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700",children:(0,a.jsx)(U.Z,{className:"h-4 w-4"})})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Category"}),(0,a.jsx)("div",{className:"mt-1",children:c.category?(0,a.jsx)(C.Z,{color:f,size:"xs",children:c.category}):(0,a.jsx)(H.Z,{className:"text-gray-400",children:"Uncategorized"})})]}),i&&(0,a.jsxs)("div",{className:"col-span-3",children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Status"}),(0,a.jsxs)("div",{className:"flex items-center gap-3 mt-2",children:[(0,a.jsx)(A.Z,{checked:c.enabled,loading:h,onChange:y}),(0,a.jsx)(H.Z,{className:"text-sm",children:c.enabled?"Plugin is enabled and visible in marketplace":"Plugin is disabled and hidden from marketplace"})]})]})]})]}),c.description&&(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Description"}),(0,a.jsx)(H.Z,{className:"mt-2",children:c.description})]}),c.keywords&&c.keywords.length>0&&(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Keywords"}),(0,a.jsx)("div",{className:"flex flex-wrap gap-2 mt-2",children:c.keywords.map((e,l)=>(0,a.jsx)(C.Z,{color:"gray",size:"xs",children:e},l))})]}),c.author&&(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Author Information"}),(0,a.jsxs)(T.Z,{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4",children:[c.author.name&&(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Name"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:c.author.name})]}),c.author.email&&(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Email"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:(0,a.jsx)("a",{href:"mailto:".concat(c.author.email),className:"text-blue-500 hover:text-blue-700",children:c.author.email})})]})]})]}),c.homepage&&(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Homepage"}),(0,a.jsxs)("a",{href:c.homepage,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 flex items-center gap-2 mt-2",children:[c.homepage,(0,a.jsx)(U.Z,{className:"h-4 w-4"})]})]}),(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Metadata"}),(0,a.jsxs)(T.Z,{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Created At"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:(0,x.ie)(c.created_at)})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Updated At"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:(0,x.ie)(c.updated_at)})]}),c.created_by&&(0,a.jsxs)("div",{className:"col-span-2",children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Created By"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:c.created_by})]})]})]})]})},B=e=>{let{accessToken:l,userRole:s}=e,[o,c]=(0,t.useState)([]),[d,m]=(0,t.useState)(!1),[x,u]=(0,t.useState)(!1),[h,g]=(0,t.useState)(!1),[j,y]=(0,t.useState)(null),[b,N]=(0,t.useState)(null),Z=!!s&&(0,R.tY)(s),f=async()=>{if(l){u(!0);try{let e=await (0,n.getClaudeCodePluginsList)(l,!1);console.log("Claude Code plugins: ".concat(JSON.stringify(e))),c(e.plugins)}catch(e){console.error("Error fetching Claude Code plugins:",e)}finally{u(!1)}}};(0,t.useEffect)(()=>{f()},[l]);let v=async()=>{if(j&&l){g(!0);try{await (0,n.deleteClaudeCodePlugin)(l,j.name),D.Z.success('Plugin "'.concat(j.displayName,'" deleted successfully')),f()}catch(e){console.error("Error deleting plugin:",e),D.Z.error("Failed to delete plugin")}finally{g(!1),y(null)}}};return(0,a.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-2 mb-4",children:[(0,a.jsx)("h1",{className:"text-2xl font-bold",children:"Claude Code Plugins"}),(0,a.jsxs)("p",{className:"text-sm text-gray-600",children:["Manage Claude Code marketplace plugins. Add, enable, disable, or delete plugins that will be available in your marketplace catalog. Enabled plugins will appear in the public marketplace at"," ",(0,a.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"/claude-code/marketplace.json"}),"."]}),(0,a.jsx)("div",{className:"mt-2",children:(0,a.jsx)(r.z,{onClick:()=>{b&&N(null),m(!0)},disabled:!l||!Z,children:"+ Add New Plugin"})})]}),b?(0,a.jsx)(q,{pluginId:b,onClose:()=>N(null),accessToken:l,isAdmin:Z,onPluginUpdated:f}):(0,a.jsx)(L,{pluginsList:o,isLoading:x,onDeleteClick:(e,l)=>{y({name:e,displayName:l})},accessToken:l,onPluginUpdated:f,isAdmin:Z,onPluginClick:e=>N(e)}),(0,a.jsx)(p,{visible:d,onClose:()=>{m(!1)},accessToken:l,onSuccess:()=>{f()}}),j&&(0,a.jsxs)(i.Z,{title:"Delete Plugin",open:null!==j,onOk:v,onCancel:()=>{y(null)},confirmLoading:h,okText:"Delete",okButtonProps:{danger:!0},children:[(0,a.jsxs)("p",{children:["Are you sure you want to delete plugin:"," ",(0,a.jsx)("strong",{children:j.displayName}),"?"]}),(0,a.jsx)("p",{children:"This action cannot be undone."})]})]})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1112-9ebdaa5e005fb7d9.js b/litellm/proxy/_experimental/out/_next/static/chunks/1112-9ebdaa5e005fb7d9.js new file mode 100644 index 00000000000..6a7f4a4ea26 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1112-9ebdaa5e005fb7d9.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1112],{41112:function(e,l,s){s.d(l,{Z:function(){return B}});var a=s(57437),t=s(2265),r=s(16312),i=s(22116),n=s(19250),o=s(4260),c=s(37592),d=s(10032),m=s(42264),x=s(43769);let{TextArea:u}=o.default,{Option:h}=c.default,g=["Development","Productivity","Learning","Security","Data & Analytics","Integration","Testing","Documentation"];var p=e=>{let{visible:l,onClose:s,accessToken:p,onSuccess:j}=e,[y]=d.Z.useForm(),[b,N]=(0,t.useState)(!1),[Z,f]=(0,t.useState)("github"),v=async e=>{if(!p){m.ZP.error("No access token available");return}if(!(0,x.$L)(e.name)){m.ZP.error("Plugin name must be kebab-case (lowercase letters, numbers, and hyphens only)");return}if(e.version&&!(0,x.Nq)(e.version)){m.ZP.error("Version must be in semantic versioning format (e.g., 1.0.0)");return}if(e.authorEmail&&!(0,x.vV)(e.authorEmail)){m.ZP.error("Invalid email format");return}if(e.homepage&&!(0,x.jv)(e.homepage)){m.ZP.error("Invalid homepage URL format");return}N(!0);try{let l={name:e.name.trim(),source:"github"===Z?{source:"github",repo:e.repo.trim()}:{source:"url",url:e.url.trim()}};e.version&&(l.version=e.version.trim()),e.description&&(l.description=e.description.trim()),(e.authorName||e.authorEmail)&&(l.author={},e.authorName&&(l.author.name=e.authorName.trim()),e.authorEmail&&(l.author.email=e.authorEmail.trim())),e.homepage&&(l.homepage=e.homepage.trim()),e.category&&(l.category=e.category),e.keywords&&(l.keywords=(0,x.jE)(e.keywords)),await (0,n.registerClaudeCodePlugin)(p,l),m.ZP.success("Plugin registered successfully"),y.resetFields(),f("github"),j(),s()}catch(e){console.error("Error registering plugin:",e),m.ZP.error("Failed to register plugin")}finally{N(!1)}},C=()=>{y.resetFields(),f("github"),s()};return(0,a.jsx)(i.Z,{title:"Add New Claude Code Plugin",open:l,onCancel:C,footer:null,width:700,className:"top-8",children:(0,a.jsxs)(d.Z,{form:y,layout:"vertical",onFinish:v,className:"mt-4",children:[(0,a.jsx)(d.Z.Item,{label:"Plugin Name",name:"name",rules:[{required:!0,message:"Please enter plugin name"},{pattern:/^[a-z0-9-]+$/,message:"Name must be kebab-case (lowercase, numbers, hyphens only)"}],tooltip:"Unique identifier in kebab-case format (e.g., my-awesome-plugin)",children:(0,a.jsx)(o.default,{placeholder:"my-awesome-plugin",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Source Type",name:"sourceType",initialValue:"github",rules:[{required:!0,message:"Please select source type"}],children:(0,a.jsxs)(c.default,{onChange:e=>{f(e),y.setFieldsValue({repo:void 0,url:void 0})},className:"rounded-lg",children:[(0,a.jsx)(h,{value:"github",children:"GitHub"}),(0,a.jsx)(h,{value:"url",children:"URL"})]})}),"github"===Z&&(0,a.jsx)(d.Z.Item,{label:"GitHub Repository",name:"repo",rules:[{required:!0,message:"Please enter repository"},{pattern:/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/,message:"Repository must be in format: org/repo"}],tooltip:"Format: organization/repository (e.g., anthropics/claude-code)",children:(0,a.jsx)(o.default,{placeholder:"anthropics/claude-code",className:"rounded-lg"})}),"url"===Z&&(0,a.jsx)(d.Z.Item,{label:"Git URL",name:"url",rules:[{required:!0,message:"Please enter git URL"}],tooltip:"Full git URL to the repository",children:(0,a.jsx)(o.default,{type:"url",placeholder:"https://github.com/org/repo.git",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Version (Optional)",name:"version",tooltip:"Semantic version (e.g., 1.0.0)",children:(0,a.jsx)(o.default,{placeholder:"1.0.0",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Description (Optional)",name:"description",tooltip:"Brief description of what the plugin does",children:(0,a.jsx)(u,{rows:3,placeholder:"A plugin that helps with...",maxLength:500,className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Category (Optional)",name:"category",tooltip:"Select a category or enter a custom one",children:(0,a.jsx)(c.default,{placeholder:"Select or type a category",allowClear:!0,showSearch:!0,optionFilterProp:"children",className:"rounded-lg",children:g.map(e=>(0,a.jsx)(h,{value:e,children:e},e))})}),(0,a.jsx)(d.Z.Item,{label:"Keywords (Optional)",name:"keywords",tooltip:"Comma-separated list of keywords for search",children:(0,a.jsx)(o.default,{placeholder:"search, web, api",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Author Name (Optional)",name:"authorName",tooltip:"Name of the plugin author or organization",children:(0,a.jsx)(o.default,{placeholder:"Your Name or Organization",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Author Email (Optional)",name:"authorEmail",rules:[{type:"email",message:"Please enter a valid email"}],tooltip:"Contact email for the plugin author",children:(0,a.jsx)(o.default,{type:"email",placeholder:"author@example.com",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{label:"Homepage (Optional)",name:"homepage",rules:[{type:"url",message:"Please enter a valid URL"}],tooltip:"URL to the plugin's homepage or documentation",children:(0,a.jsx)(o.default,{type:"url",placeholder:"https://example.com",className:"rounded-lg"})}),(0,a.jsx)(d.Z.Item,{className:"mb-0 mt-6",children:(0,a.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,a.jsx)(r.z,{variant:"secondary",onClick:C,disabled:b,children:"Cancel"}),(0,a.jsx)(r.z,{type:"submit",loading:b,children:b?"Registering...":"Register Plugin"})]})})]})})},j=s(23639),y=s(74998),b=s(44633),N=s(86462),Z=s(49084),f=s(71594),v=s(24525),C=s(41649),w=s(78489),P=s(21626),k=s(97214),S=s(28241),_=s(58834),z=s(69552),I=s(71876),E=s(99981),A=s(63709),D=s(9114),L=e=>{let{pluginsList:l,isLoading:s,onDeleteClick:r,accessToken:i,onPluginUpdated:o,isAdmin:c,onPluginClick:d}=e,[m,u]=(0,t.useState)([{id:"created_at",desc:!0}]),[h,g]=(0,t.useState)(null),p=e=>e?new Date(e).toLocaleString():"-",L=e=>{navigator.clipboard.writeText(e),D.ZP.success("Copied to clipboard!")},R=async e=>{if(i){g(e.id);try{e.enabled?(await (0,n.disableClaudeCodePlugin)(i,e.name),D.ZP.success('Plugin "'.concat(e.name,'" disabled'))):(await (0,n.enableClaudeCodePlugin)(i,e.name),D.ZP.success('Plugin "'.concat(e.name,'" enabled'))),o()}catch(e){D.ZP.error("Failed to toggle plugin status")}finally{g(null)}}},F=[{header:"Plugin Name",accessorKey:"name",cell:e=>{let{row:l}=e,s=l.original,t=s.name||"";return(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(E.Z,{title:t,children:(0,a.jsx)(w.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 min-w-[150px] justify-start",onClick:()=>d(s.id),children:t})}),(0,a.jsx)(E.Z,{title:"Copy Plugin ID",children:(0,a.jsx)(j.Z,{onClick:e=>{e.stopPropagation(),L(s.id)},className:"cursor-pointer text-gray-500 hover:text-blue-500 text-xs"})})]})}},{header:"Version",accessorKey:"version",cell:e=>{let{row:l}=e,s=l.original.version||"N/A";return(0,a.jsx)("span",{className:"text-xs text-gray-600",children:s})}},{header:"Description",accessorKey:"description",cell:e=>{let{row:l}=e,s=l.original.description||"No description";return(0,a.jsx)(E.Z,{title:s,children:(0,a.jsx)("span",{className:"text-xs text-gray-600 block max-w-[300px] truncate",children:s})})}},{header:"Category",accessorKey:"category",cell:e=>{let{row:l}=e,s=l.original.category;if(!s)return(0,a.jsx)(C.Z,{color:"gray",className:"text-xs font-normal",size:"xs",children:"Uncategorized"});let t=(0,x.LH)(s);return(0,a.jsx)(C.Z,{color:t,className:"text-xs font-normal",size:"xs",children:s})}},{header:"Enabled",accessorKey:"enabled",cell:e=>{let{row:l}=e,s=l.original;return(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(C.Z,{color:s.enabled?"green":"gray",className:"text-xs font-normal",size:"xs",children:s.enabled?"Yes":"No"}),c&&(0,a.jsx)(E.Z,{title:s.enabled?"Disable plugin":"Enable plugin",children:(0,a.jsx)(A.Z,{size:"small",checked:s.enabled,loading:h===s.id,onChange:()=>R(s)})})]})}},{header:"Created At",accessorKey:"created_at",cell:e=>{let{row:l}=e,s=l.original;return(0,a.jsx)(E.Z,{title:s.created_at,children:(0,a.jsx)("span",{className:"text-xs",children:p(s.created_at)})})}},...c?[{header:"Actions",id:"actions",enableSorting:!1,cell:e=>{let{row:l}=e,s=l.original;return(0,a.jsx)("div",{className:"flex items-center gap-1",children:(0,a.jsx)(E.Z,{title:"Delete plugin",children:(0,a.jsx)(w.Z,{size:"xs",variant:"light",color:"red",onClick:e=>{e.stopPropagation(),r(s.name,s.name)},icon:y.Z,className:"text-red-500 hover:text-red-700 hover:bg-red-50"})})})}}]:[]],U=(0,f.b7)({data:l,columns:F,state:{sorting:m},onSortingChange:u,getCoreRowModel:(0,v.sC)(),getSortedRowModel:(0,v.tj)(),enableSorting:!0});return(0,a.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,a.jsx)("div",{className:"overflow-x-auto",children:(0,a.jsxs)(P.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,a.jsx)(_.Z,{children:U.getHeaderGroups().map(e=>(0,a.jsx)(I.Z,{children:e.headers.map(e=>(0,a.jsx)(z.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.getCanSort()?e.column.getToggleSortingHandler():void 0,children:(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,f.ie)(e.column.columnDef.header,e.getContext())}),e.column.getCanSort()&&(0,a.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,a.jsx)(b.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,a.jsx)(N.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,a.jsx)(Z.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,a.jsx)(k.Z,{children:s?(0,a.jsx)(I.Z,{children:(0,a.jsx)(S.Z,{colSpan:F.length,className:"h-8 text-center",children:(0,a.jsx)("div",{className:"text-center text-gray-500",children:(0,a.jsx)("p",{children:"Loading..."})})})}):l&&l.length>0?U.getRowModel().rows.map(e=>(0,a.jsx)(I.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,a.jsx)(S.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,f.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,a.jsx)(I.Z,{children:(0,a.jsx)(S.Z,{colSpan:F.length,className:"h-8 text-center",children:(0,a.jsx)("div",{className:"text-center text-gray-500",children:(0,a.jsx)("p",{children:"No plugins found. Add one to get started."})})})})})]})})})},R=s(20347),F=s(10900),U=s(3477),O=s(12514),T=s(67101),H=s(84264),K=s(96761),V=s(10353),q=e=>{let{pluginId:l,onClose:s,accessToken:r,isAdmin:i,onPluginUpdated:o}=e,[c,d]=(0,t.useState)(null),[m,u]=(0,t.useState)(!0),[h,g]=(0,t.useState)(!1);(0,t.useEffect)(()=>{p()},[l,r]);let p=async()=>{if(r){u(!0);try{let e=await (0,n.getClaudeCodePluginDetails)(r,l);d(e.plugin)}catch(e){console.error("Error fetching plugin info:",e),D.ZP.error("Failed to load plugin information")}finally{u(!1)}}},y=async()=>{if(r&&c){g(!0);try{c.enabled?(await (0,n.disableClaudeCodePlugin)(r,c.name),D.ZP.success('Plugin "'.concat(c.name,'" disabled'))):(await (0,n.enableClaudeCodePlugin)(r,c.name),D.ZP.success('Plugin "'.concat(c.name,'" enabled'))),o(),p()}catch(e){D.ZP.error("Failed to toggle plugin status")}finally{g(!1)}}},b=e=>{navigator.clipboard.writeText(e),D.ZP.success("Copied to clipboard!")};if(m)return(0,a.jsx)("div",{className:"flex items-center justify-center p-8",children:(0,a.jsx)(V.Z,{size:"large"})});if(!c)return(0,a.jsxs)("div",{className:"p-8 text-center text-gray-500",children:[(0,a.jsx)("p",{children:"Plugin not found"}),(0,a.jsx)(w.Z,{className:"mt-4",onClick:s,children:"Go Back"})]});let N=(0,x.aB)(c),Z=(0,x.OB)(c.source),f=(0,x.LH)(c.category);return(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsxs)("div",{className:"flex items-center gap-3 mb-6",children:[(0,a.jsx)(F.Z,{className:"h-5 w-5 cursor-pointer text-gray-500 hover:text-gray-700",onClick:s}),(0,a.jsx)("h2",{className:"text-2xl font-bold",children:c.name}),c.version&&(0,a.jsxs)(C.Z,{color:"blue",size:"xs",children:["v",c.version]}),c.category&&(0,a.jsx)(C.Z,{color:f,size:"xs",children:c.category}),(0,a.jsx)(C.Z,{color:c.enabled?"green":"gray",size:"xs",children:c.enabled?"Enabled":"Disabled"})]}),(0,a.jsx)(O.Z,{children:(0,a.jsxs)("div",{className:"flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"flex-1",children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs mb-2",children:"Install Command"}),(0,a.jsx)("div",{className:"font-mono bg-gray-100 px-3 py-2 rounded text-sm",children:N})]}),(0,a.jsx)(E.Z,{title:"Copy install command",children:(0,a.jsx)(w.Z,{size:"xs",variant:"secondary",icon:j.Z,onClick:()=>b(N),className:"ml-4",children:"Copy"})})]})}),(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Plugin Details"}),(0,a.jsxs)(T.Z,{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 mt-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Plugin ID"}),(0,a.jsxs)("div",{className:"flex items-center gap-2 mt-1",children:[(0,a.jsx)(H.Z,{className:"font-mono text-xs",children:c.id}),(0,a.jsx)(j.Z,{className:"cursor-pointer text-gray-500 hover:text-blue-500 text-xs",onClick:()=>b(c.id)})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Name"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:c.name})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Version"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:c.version||"N/A"})]}),(0,a.jsxs)("div",{className:"col-span-2",children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Source"}),(0,a.jsxs)("div",{className:"flex items-center gap-2 mt-1",children:[(0,a.jsx)(H.Z,{className:"font-semibold",children:(0,x.i5)(c.source)}),Z&&(0,a.jsx)("a",{href:Z,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700",children:(0,a.jsx)(U.Z,{className:"h-4 w-4"})})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Category"}),(0,a.jsx)("div",{className:"mt-1",children:c.category?(0,a.jsx)(C.Z,{color:f,size:"xs",children:c.category}):(0,a.jsx)(H.Z,{className:"text-gray-400",children:"Uncategorized"})})]}),i&&(0,a.jsxs)("div",{className:"col-span-3",children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Status"}),(0,a.jsxs)("div",{className:"flex items-center gap-3 mt-2",children:[(0,a.jsx)(A.Z,{checked:c.enabled,loading:h,onChange:y}),(0,a.jsx)(H.Z,{className:"text-sm",children:c.enabled?"Plugin is enabled and visible in marketplace":"Plugin is disabled and hidden from marketplace"})]})]})]})]}),c.description&&(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Description"}),(0,a.jsx)(H.Z,{className:"mt-2",children:c.description})]}),c.keywords&&c.keywords.length>0&&(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Keywords"}),(0,a.jsx)("div",{className:"flex flex-wrap gap-2 mt-2",children:c.keywords.map((e,l)=>(0,a.jsx)(C.Z,{color:"gray",size:"xs",children:e},l))})]}),c.author&&(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Author Information"}),(0,a.jsxs)(T.Z,{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4",children:[c.author.name&&(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Name"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:c.author.name})]}),c.author.email&&(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Email"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:(0,a.jsx)("a",{href:"mailto:".concat(c.author.email),className:"text-blue-500 hover:text-blue-700",children:c.author.email})})]})]})]}),c.homepage&&(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Homepage"}),(0,a.jsxs)("a",{href:c.homepage,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 flex items-center gap-2 mt-2",children:[c.homepage,(0,a.jsx)(U.Z,{className:"h-4 w-4"})]})]}),(0,a.jsxs)(O.Z,{children:[(0,a.jsx)(K.Z,{children:"Metadata"}),(0,a.jsxs)(T.Z,{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Created At"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:(0,x.ie)(c.created_at)})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Updated At"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:(0,x.ie)(c.updated_at)})]}),c.created_by&&(0,a.jsxs)("div",{className:"col-span-2",children:[(0,a.jsx)(H.Z,{className:"text-gray-600 text-xs",children:"Created By"}),(0,a.jsx)(H.Z,{className:"font-semibold mt-1",children:c.created_by})]})]})]})]})},B=e=>{let{accessToken:l,userRole:s}=e,[o,c]=(0,t.useState)([]),[d,m]=(0,t.useState)(!1),[x,u]=(0,t.useState)(!1),[h,g]=(0,t.useState)(!1),[j,y]=(0,t.useState)(null),[b,N]=(0,t.useState)(null),Z=!!s&&(0,R.tY)(s),f=async()=>{if(l){u(!0);try{let e=await (0,n.getClaudeCodePluginsList)(l,!1);console.log("Claude Code plugins: ".concat(JSON.stringify(e))),c(e.plugins)}catch(e){console.error("Error fetching Claude Code plugins:",e)}finally{u(!1)}}};(0,t.useEffect)(()=>{f()},[l]);let v=async()=>{if(j&&l){g(!0);try{await (0,n.deleteClaudeCodePlugin)(l,j.name),D.ZP.success('Plugin "'.concat(j.displayName,'" deleted successfully')),f()}catch(e){console.error("Error deleting plugin:",e),D.ZP.error("Failed to delete plugin")}finally{g(!1),y(null)}}};return(0,a.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-2 mb-4",children:[(0,a.jsx)("h1",{className:"text-2xl font-bold",children:"Claude Code Plugins"}),(0,a.jsxs)("p",{className:"text-sm text-gray-600",children:["Manage Claude Code marketplace plugins. Add, enable, disable, or delete plugins that will be available in your marketplace catalog. Enabled plugins will appear in the public marketplace at"," ",(0,a.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"/claude-code/marketplace.json"}),"."]}),(0,a.jsx)("div",{className:"mt-2",children:(0,a.jsx)(r.z,{onClick:()=>{b&&N(null),m(!0)},disabled:!l||!Z,children:"+ Add New Plugin"})})]}),b?(0,a.jsx)(q,{pluginId:b,onClose:()=>N(null),accessToken:l,isAdmin:Z,onPluginUpdated:f}):(0,a.jsx)(L,{pluginsList:o,isLoading:x,onDeleteClick:(e,l)=>{y({name:e,displayName:l})},accessToken:l,onPluginUpdated:f,isAdmin:Z,onPluginClick:e=>N(e)}),(0,a.jsx)(p,{visible:d,onClose:()=>{m(!1)},accessToken:l,onSuccess:()=>{f()}}),j&&(0,a.jsxs)(i.Z,{title:"Delete Plugin",open:null!==j,onOk:v,onCancel:()=>{y(null)},confirmLoading:h,okText:"Delete",okButtonProps:{danger:!0},children:[(0,a.jsxs)("p",{children:["Are you sure you want to delete plugin:"," ",(0,a.jsx)("strong",{children:j.displayName}),"?"]}),(0,a.jsx)("p",{children:"This action cannot be undone."})]})]})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1208-5caf6d9856cc3f13.js b/litellm/proxy/_experimental/out/_next/static/chunks/1208-7c5c59dc6afa9085.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/chunks/1208-5caf6d9856cc3f13.js rename to litellm/proxy/_experimental/out/_next/static/chunks/1208-7c5c59dc6afa9085.js diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1658-c301cddaf7772753.js b/litellm/proxy/_experimental/out/_next/static/chunks/1658-c301cddaf7772753.js deleted file mode 100644 index 730804d53de..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/1658-c301cddaf7772753.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1658],{71658:function(e,l,t){t.d(l,{Z:function(){return l1}});var s=t(57437),a=t(19250),r=t(11713),i=t(90246),n=t(39760);let o=(0,i.n)("credentials"),d=()=>{let{accessToken:e}=(0,n.Z)();return(0,r.a)({queryKey:o.list({}),queryFn:async()=>await (0,a.credentialListCall)(e),enabled:!!e})},c=(0,i.n)("modelCostMap"),m=()=>(0,r.a)({queryKey:c.list({}),queryFn:async()=>await (0,a.modelCostMap)(),staleTime:6e4,gcTime:6e4});var u=t(52178),h=t(55584),x=t(47359),p=t(71594),g=t(24525),f=t(2265),j=t(19130),v=t(73705),_=t(5545),b=t(44633),y=t(86462),N=t(3837),w=t(49084);let Z=e=>{let{sortState:l,onSortChange:t}=e,a=[{key:"asc",label:"Ascending",icon:(0,s.jsx)(b.Z,{className:"h-4 w-4"})},{key:"desc",label:"Descending",icon:(0,s.jsx)(y.Z,{className:"h-4 w-4"})},{key:"reset",label:"Reset",icon:(0,s.jsx)(N.Z,{className:"h-4 w-4"})}];return(0,s.jsx)(v.Z,{menu:{items:a,onClick:e=>{let{key:l}=e;"asc"===l?t("asc"):"desc"===l?t("desc"):"reset"===l&&t(!1)},selectable:!0,selectedKeys:l?[l]:[]},trigger:["click"],autoAdjustOverflow:!0,children:(0,s.jsx)(_.ZP,{type:"text",onClick:e=>e.stopPropagation(),icon:"asc"===l?(0,s.jsx)(b.Z,{className:"h-4 w-4"}):"desc"===l?(0,s.jsx)(y.Z,{className:"h-4 w-4"}):(0,s.jsx)(w.Z,{className:"h-4 w-4"}),className:l?"text-blue-500 hover:text-blue-600":"text-gray-400 hover:text-blue-500"})})};function C(e){let{data:l=[],columns:t,isLoading:a=!1,sorting:r=[],onSortingChange:i,pagination:n,onPaginationChange:o,enablePagination:d=!1}=e,[c]=f.useState("onChange"),[m,u]=f.useState({}),[h,x]=f.useState({}),v=(0,p.b7)({data:l,columns:t,state:{sorting:r,columnSizing:m,columnVisibility:h,...d&&n?{pagination:n}:{}},columnResizeMode:c,onSortingChange:i,onColumnSizingChange:u,onColumnVisibilityChange:x,...d&&o?{onPaginationChange:o}:{},getCoreRowModel:(0,g.sC)(),...d?{getPaginationRowModel:(0,g.G_)()}:{},enableSorting:!0,enableColumnResizing:!0,manualSorting:!0,defaultColumn:{minSize:40,maxSize:500}});return(0,s.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,s.jsx)("div",{className:"overflow-x-auto",children:(0,s.jsx)("div",{className:"relative min-w-full",children:(0,s.jsxs)(j.iA,{className:"[&_td]:py-2 [&_th]:py-2 w-full",children:[(0,s.jsx)(j.ss,{children:v.getHeaderGroups().map(e=>(0,s.jsx)(j.SC,{children:e.headers.map(e=>{var l;return(0,s.jsxs)(j.xs,{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)] w-[120px] ml-8":""," ").concat((null===(l=e.column.columnDef.meta)||void 0===l?void 0:l.className)||""),style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},children:[(0,s.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,s.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,p.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&e.column.getCanSort()&&i&&(0,s.jsx)(Z,{sortState:!1!==e.column.getIsSorted()&&e.column.getIsSorted(),onSortChange:l=>{!1===l?i([]):i([{id:e.column.id,desc:"desc"===l}])},columnId:e.column.id})]}),e.column.getCanResize()&&(0,s.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,s.jsx)(j.RM,{children:a?(0,s.jsx)(j.SC,{children:(0,s.jsx)(j.pj,{colSpan:t.length,className:"h-8 text-center",children:(0,s.jsx)("div",{className:"text-center text-gray-500",children:(0,s.jsx)("p",{children:"\uD83D\uDE85 Loading models..."})})})}):v.getRowModel().rows.length>0?v.getRowModel().rows.map(e=>(0,s.jsx)(j.SC,{children:e.getVisibleCells().map(e=>{var l;return(0,s.jsx)(j.pj,{className:"py-0.5 ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""," ").concat((null===(l=e.column.columnDef.meta)||void 0===l?void 0:l.className)||""),style:{width:"actions"===e.column.id?120:e.column.getSize(),position:"actions"===e.column.id?"sticky":"relative",right:"actions"===e.column.id?0:"auto"},children:(0,p.ie)(e.column.columnDef.cell,e.getContext())},e.id)})},e.id)):(0,s.jsx)(j.SC,{children:(0,s.jsx)(j.pj,{colSpan:t.length,className:"h-8 text-center",children:(0,s.jsx)("div",{className:"text-center text-gray-500",children:(0,s.jsx)("p",{children:"No models found"})})})})})]})})})})}var k=t(45589),S=t(74998),A=t(41649),E=t(78489),P=t(47323),M=t(99981),L=t(42673);let F=e=>{let{provider:l,className:t="w-4 h-4"}=e,[a,r]=(0,f.useState)(!1),{logo:i}=(0,L.dr)(l);return a||!i?(0,s.jsx)("div",{className:"".concat(t," rounded-full bg-gray-200 flex items-center justify-center text-xs"),children:(null==l?void 0:l.charAt(0))||"-"}):(0,s.jsx)("img",{src:i,alt:"".concat(l," logo"),className:t,onError:()=>r(!0)})},I=(e,l,t,a,r,i,n,o,d,c)=>[{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Model ID"}),accessorKey:"model_info.id",enableSorting:!1,cell:e=>{let{row:l}=e,t=l.original;return(0,s.jsx)(M.Z,{title:t.model_info.id,children:(0,s.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 max-w-[15ch]",onClick:()=>a(t.model_info.id),children:t.model_info.id})})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Model Information"}),accessorKey:"model_name",size:250,cell:e=>{let{row:l}=e,t=l.original,a=i(l.original)||"-",r=(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("strong",{children:"Provider:"})," ",t.provider||"-"]}),(0,s.jsxs)("div",{children:[(0,s.jsx)("strong",{children:"Public Model Name:"})," ",a]}),(0,s.jsxs)("div",{children:[(0,s.jsx)("strong",{children:"LiteLLM Model Name:"})," ",t.litellm_model_name||"-"]})]});return(0,s.jsx)(M.Z,{title:r,children:(0,s.jsxs)("div",{className:"flex items-start space-x-2 min-w-0 w-full max-w-[250px]",children:[(0,s.jsx)("div",{className:"flex-shrink-0 mt-0.5",children:t.provider?(0,s.jsx)(F,{provider:t.provider}):(0,s.jsx)("div",{className:"w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",children:"-"})}),(0,s.jsxs)("div",{className:"flex flex-col min-w-0 flex-1",children:[(0,s.jsx)("div",{className:"text-xs font-medium text-gray-900 truncate max-w-[210px]",children:a}),(0,s.jsx)("div",{className:"text-xs text-gray-500 truncate mt-0.5 max-w-[210px]",children:t.litellm_model_name||"-"})]})]})})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Credentials"}),accessorKey:"litellm_credential_name",enableSorting:!1,size:180,cell:e=>{var l;let{row:t}=e,a=null===(l=t.original.litellm_params)||void 0===l?void 0:l.litellm_credential_name;return a?(0,s.jsx)(M.Z,{title:"Credential: ".concat(a),children:(0,s.jsxs)("div",{className:"flex items-center space-x-2 max-w-[180px]",children:[(0,s.jsx)(k.Z,{className:"w-4 h-4 text-blue-500 flex-shrink-0"}),(0,s.jsx)("span",{className:"text-xs truncate",title:a,children:a})]})}):(0,s.jsxs)("div",{className:"flex items-center space-x-2 max-w-[180px]",children:[(0,s.jsx)(k.Z,{className:"w-4 h-4 text-gray-300 flex-shrink-0"}),(0,s.jsx)("span",{className:"text-xs text-gray-400",children:"No credentials"})]})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Created By"}),accessorKey:"model_info.created_by",sortingFn:"datetime",size:160,cell:e=>{var l;let{row:t}=e,a=t.original,r=!(null===(l=a.model_info)||void 0===l?void 0:l.db_model),i=a.model_info.created_by,n=a.model_info.created_at?new Date(a.model_info.created_at).toLocaleDateString():null;return(0,s.jsxs)("div",{className:"flex flex-col min-w-0 max-w-[160px]",children:[(0,s.jsx)("div",{className:"text-xs font-medium text-gray-900 truncate",title:r?"Defined in config":i||"Unknown",children:r?"Defined in config":i||"Unknown"}),(0,s.jsx)("div",{className:"text-xs text-gray-500 truncate mt-0.5",title:r?"Config file":n||"Unknown date",children:r?"-":n||"Unknown date"})]})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Updated At"}),accessorKey:"model_info.updated_at",sortingFn:"datetime",cell:e=>{let{row:l}=e,t=l.original;return(0,s.jsx)("span",{className:"text-xs",children:t.model_info.updated_at?new Date(t.model_info.updated_at).toLocaleDateString():"-"})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Costs"}),accessorKey:"input_cost",size:120,cell:e=>{let{row:l}=e,t=l.original,a=t.input_cost,r=t.output_cost;return a||r?(0,s.jsx)(M.Z,{title:"Cost per 1M tokens",children:(0,s.jsxs)("div",{className:"flex flex-col min-w-0 max-w-[120px]",children:[a&&(0,s.jsxs)("div",{className:"text-xs font-medium text-gray-900 truncate",children:["In: $",a]}),r&&(0,s.jsxs)("div",{className:"text-xs text-gray-500 truncate mt-0.5",children:["Out: $",r]})]})}):(0,s.jsx)("div",{className:"max-w-[120px]",children:(0,s.jsx)("span",{className:"text-xs text-gray-400",children:"-"})})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Team ID"}),accessorKey:"model_info.team_id",enableSorting:!1,cell:e=>{let{row:l}=e,t=l.original;return t.model_info.team_id?(0,s.jsx)("div",{className:"overflow-hidden",children:(0,s.jsx)(M.Z,{title:t.model_info.team_id,children:(0,s.jsxs)(E.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:()=>r(t.model_info.team_id),children:[t.model_info.team_id.slice(0,7),"..."]})})}):"-"}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Model Access Group"}),accessorKey:"model_info.model_access_group",enableSorting:!1,cell:e=>{let{row:l}=e,t=l.original,a=t.model_info.access_groups;if(!a||0===a.length)return"-";let r=t.model_info.id,i=d.has(r),n=a.length>1,o=()=>{let e=new Set(d);i?e.delete(r):e.add(r),c(e)};return(0,s.jsxs)("div",{className:"flex items-center gap-1 overflow-hidden",children:[(0,s.jsx)(A.Z,{size:"xs",color:"blue",className:"text-xs px-1.5 py-0.5 h-5 leading-tight flex-shrink-0",children:a[0]}),(i||!n&&2===a.length)&&a.slice(1).map((e,l)=>(0,s.jsx)(A.Z,{size:"xs",color:"blue",className:"text-xs px-1.5 py-0.5 h-5 leading-tight flex-shrink-0",children:e},l+1)),n&&(0,s.jsx)("button",{onClick:e=>{e.stopPropagation(),o()},className:"text-xs text-blue-600 hover:text-blue-800 px-1 py-0.5 rounded hover:bg-blue-50 h-5 leading-tight flex-shrink-0 whitespace-nowrap",children:i?"−":"+".concat(a.length-1)})]})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Status"}),accessorKey:"model_info.db_model",cell:e=>{let{row:l}=e,t=l.original;return(0,s.jsx)("div",{className:"\n inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium\n ".concat(t.model_info.db_model?"bg-blue-50 text-blue-600":"bg-gray-100 text-gray-600","\n "),children:t.model_info.db_model?"DB Model":"Config Model"})}},{id:"actions",header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Actions"}),cell:t=>{var r,i;let{row:n}=t,o=n.original,d="Admin"===e||(null===(r=o.model_info)||void 0===r?void 0:r.created_by)===l,c=!(null===(i=o.model_info)||void 0===i?void 0:i.db_model);return(0,s.jsx)("div",{className:"flex items-center justify-end gap-2 pr-4",children:c?(0,s.jsx)(M.Z,{title:"Config model cannot be deleted on the dashboard. Please delete it from the config file.",children:(0,s.jsx)(P.Z,{icon:S.Z,size:"sm",className:"opacity-50 cursor-not-allowed"})}):(0,s.jsx)(M.Z,{title:"Delete model",children:(0,s.jsx)(P.Z,{icon:S.Z,size:"sm",onClick:()=>{d&&a(o.model_info.id)},className:d?"cursor-pointer hover:text-red-600":"opacity-50 cursor-not-allowed"})})})}}],T=e=>{var l;return(null==e?void 0:null===(l=e.model_info)||void 0===l?void 0:l.team_public_model_name)?e.model_info.team_public_model_name:(null==e?void 0:e.model_name)||"-"};var R=t(15424),O=t(67101),V=t(27281),q=t(57365),z=t(29706),D=t(84264),B=t(50337),G=t(10353),U=t(7310),H=t.n(U);let K=(e,l)=>{if(!(null==e?void 0:e.data))return{data:[]};let t=JSON.parse(JSON.stringify(e.data));for(let e=0;e{let[l]=e;return"model"!==l&&"api_base"!==l}))),t[e].provider=c,t[e].input_cost=m,t[e].output_cost=u,t[e].litellm_model_name=n,t[e].input_cost&&(t[e].input_cost=(1e6*Number(t[e].input_cost)).toFixed(2)),t[e].output_cost&&(t[e].output_cost=(1e6*Number(t[e].output_cost)).toFixed(2)),t[e].max_tokens=h,t[e].max_input_tokens=x,t[e].api_base=null==i?void 0:null===(r=i.litellm_params)||void 0===r?void 0:r.api_base,t[e].cleanedLitellmParams=p}return{data:t}};var J=e=>{let{selectedModelGroup:l,setSelectedModelGroup:t,availableModelGroups:a,availableModelAccessGroups:r,setSelectedModelId:i,setSelectedTeamId:o}=e,{data:d,isLoading:c}=m(),{userId:h,userRole:p,premiumUser:g}=(0,n.Z)(),{data:j,isLoading:v}=(0,x.y2)(),[_,b]=(0,f.useState)(""),[y,N]=(0,f.useState)(""),[w,Z]=(0,f.useState)("current_team"),[k,S]=(0,f.useState)("personal"),[A,E]=(0,f.useState)(!1),[P,M]=(0,f.useState)(null),[L,F]=(0,f.useState)(new Set),[U,J]=(0,f.useState)(1),[W]=(0,f.useState)(50),[Y,$]=(0,f.useState)({pageIndex:0,pageSize:50}),[X,Q]=(0,f.useState)([]),ee=(0,f.useMemo)(()=>H()(e=>{N(e),J(1),$(e=>({...e,pageIndex:0}))},200),[]);(0,f.useEffect)(()=>(ee(_),()=>{ee.cancel()}),[_,ee]);let el="personal"===k?void 0:k.team_id,et=(0,f.useMemo)(()=>{if(0===X.length)return;let e=X[0];return({input_cost:"costs",model_info_db_model:"status",model_info_created_by:"created_at",model_info_updated_at:"updated_at"})[e.id]||e.id},[X]),es=(0,f.useMemo)(()=>{if(0!==X.length)return X[0].desc?"desc":"asc"},[X]),{data:ea,isLoading:er}=(0,u.XP)(U,W,y||void 0,void 0,el,et,es),ei=er||c,en=e=>null!=d&&"object"==typeof d&&e in d?d[e].litellm_provider:"openai",eo=(0,f.useMemo)(()=>ea?K(ea,en):{data:[]},[ea,d]),ed=(0,f.useMemo)(()=>{var e,l,t,s;return ea?{total_count:null!==(e=ea.total_count)&&void 0!==e?e:0,current_page:null!==(l=ea.current_page)&&void 0!==l?l:1,total_pages:null!==(t=ea.total_pages)&&void 0!==t?t:1,size:null!==(s=ea.size)&&void 0!==s?s:W}:{total_count:0,current_page:1,total_pages:1,size:W}},[ea,W]),ec=(0,f.useMemo)(()=>eo&&eo.data&&0!==eo.data.length?eo.data.filter(e=>{var t,s;let a="all"===l||e.model_name===l||!l||"wildcard"===l&&(null===(t=e.model_name)||void 0===t?void 0:t.includes("*")),r="all"===P||(null===(s=e.model_info.access_groups)||void 0===s?void 0:s.includes(P))||!P;return a&&r}):[],[eo,l,P]);return(0,f.useEffect)(()=>{$(e=>({...e,pageIndex:0})),J(1)},[l,P]),(0,f.useEffect)(()=>{J(1),$(e=>({...e,pageIndex:0}))},[el]),(0,f.useEffect)(()=>{J(1),$(e=>({...e,pageIndex:0}))},[X]),(0,s.jsx)(z.Z,{children:(0,s.jsx)(O.Z,{children:(0,s.jsx)("div",{className:"flex flex-col space-y-4",children:(0,s.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,s.jsxs)("div",{className:"border-b px-6 py-4 bg-gray-50",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsxs)("div",{className:"flex items-center gap-4",children:[(0,s.jsx)(D.Z,{className:"text-lg font-semibold text-gray-900",children:"Current Team:"}),ei?(0,s.jsx)(B.Z.Input,{active:!0,style:{width:320,height:36}}):(0,s.jsxs)(V.Z,{className:"w-80",defaultValue:"personal",value:"personal"===k?"personal":k.team_id,onValueChange:e=>{if("personal"===e)S("personal"),J(1),$(e=>({...e,pageIndex:0}));else{let l=null==j?void 0:j.find(l=>l.team_id===e);l&&(S(l),J(1),$(e=>({...e,pageIndex:0})))}},children:[(0,s.jsx)(q.Z,{value:"personal",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full"}),(0,s.jsx)("span",{className:"font-medium",children:"Personal"})]})}),v?(0,s.jsx)(q.Z,{value:"loading",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(G.Z,{size:"small"}),(0,s.jsx)("span",{className:"font-medium text-gray-500",children:"Loading teams..."})]})}):null==j?void 0:j.filter(e=>e.team_id).map(e=>(0,s.jsx)(q.Z,{value:e.team_id,children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,s.jsx)("span",{className:"font-medium",children:e.team_alias?"".concat(e.team_alias.slice(0,30),"..."):"Team ".concat(e.team_id.slice(0,30),"...")})]})},e.team_id))]})]}),(0,s.jsxs)("div",{className:"flex items-center gap-4",children:[(0,s.jsx)(D.Z,{className:"text-lg font-semibold text-gray-900",children:"View:"}),ei?(0,s.jsx)(B.Z.Input,{active:!0,style:{width:256,height:36}}):(0,s.jsxs)(V.Z,{className:"w-64",defaultValue:"current_team",value:w,onValueChange:e=>Z(e),children:[(0,s.jsx)(q.Z,{value:"current_team",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-purple-500 rounded-full"}),(0,s.jsx)("span",{className:"font-medium",children:"Current Team Models"})]})}),(0,s.jsx)(q.Z,{value:"all",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-gray-500 rounded-full"}),(0,s.jsx)("span",{className:"font-medium",children:"All Available Models"})]})})]})]})]}),"current_team"===w&&(0,s.jsxs)("div",{className:"flex items-start gap-2 mt-3",children:[(0,s.jsx)(R.Z,{className:"text-gray-400 mt-0.5 flex-shrink-0 text-xs"}),(0,s.jsx)("div",{className:"text-xs text-gray-500",children:"personal"===k?(0,s.jsxs)("span",{children:["To access these models: Create a Virtual Key without selecting a team on the"," ",(0,s.jsx)("a",{href:"/public?login=success&page=api-keys",className:"text-gray-600 hover:text-gray-800 underline",children:"Virtual Keys page"})]}):(0,s.jsxs)("span",{children:['To access these models: Create a Virtual Key and select Team as "',"string"!=typeof k?k.team_alias||k.team_id:"",'" on the'," ",(0,s.jsx)("a",{href:"/public?login=success&page=api-keys",className:"text-gray-600 hover:text-gray-800 underline",children:"Virtual Keys page"})]})})]})]}),(0,s.jsx)("div",{className:"border-b px-6 py-4",children:(0,s.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,s.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,s.jsxs)("div",{className:"relative w-64",children:[(0,s.jsx)("input",{type:"text",placeholder:"Search model names...",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:_,onChange:e=>b(e.target.value)}),(0,s.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,s.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,s.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ".concat(A?"bg-gray-100":""),onClick:()=>E(!A),children:[(0,s.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,s.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"]}),(0,s.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>{b(""),t("all"),M(null),S("personal"),Z("current_team"),J(1),$({pageIndex:0,pageSize:50}),Q([])},children:[(0,s.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,s.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"]})]}),A&&(0,s.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,s.jsx)("div",{className:"w-64",children:(0,s.jsxs)(V.Z,{value:null!=l?l:"all",onValueChange:e=>t("all"===e?"all":e),placeholder:"Filter by Public Model Name",children:[(0,s.jsx)(q.Z,{value:"all",children:"All Models"}),(0,s.jsx)(q.Z,{value:"wildcard",children:"Wildcard Models (*)"}),a.map((e,l)=>(0,s.jsx)(q.Z,{value:e,children:e},l))]})}),(0,s.jsx)("div",{className:"w-64",children:(0,s.jsxs)(V.Z,{value:null!=P?P:"all",onValueChange:e=>M("all"===e?null:e),placeholder:"Filter by Model Access Group",children:[(0,s.jsx)(q.Z,{value:"all",children:"All Model Access Groups"}),r.map((e,l)=>(0,s.jsx)(q.Z,{value:e,children:e},l))]})})]}),(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[ei?(0,s.jsx)(B.Z.Input,{active:!0,style:{width:184,height:20}}):(0,s.jsx)("span",{className:"text-sm text-gray-700",children:ed.total_count>0?"Showing ".concat((U-1)*W+1," - ").concat(Math.min(U*W,ed.total_count)," of ").concat(ed.total_count," results"):"Showing 0 results"}),(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[ei?(0,s.jsx)(B.Z.Button,{active:!0,style:{width:84,height:30}}):(0,s.jsx)("button",{onClick:()=>{J(U-1),$(e=>({...e,pageIndex:0}))},disabled:1===U,className:"px-3 py-1 text-sm border rounded-md ".concat(1===U?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Previous"}),ei?(0,s.jsx)(B.Z.Button,{active:!0,style:{width:56,height:30}}):(0,s.jsx)("button",{onClick:()=>{J(U+1),$(e=>({...e,pageIndex:0}))},disabled:U>=ed.total_pages,className:"px-3 py-1 text-sm border rounded-md ".concat(U>=ed.total_pages?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Next"})]})]})]})}),(0,s.jsx)(C,{columns:I(p,h,g,i,o,T,()=>{},()=>{},L,F),data:ec,isLoading:er,sorting:X,onSortingChange:Q,pagination:Y,onPaginationChange:$,enablePagination:!0})]})})})})},W=t(96761),Y=t(12221);let $={"BadRequestError (400)":"BadRequestErrorRetries","AuthenticationError (401)":"AuthenticationErrorRetries","TimeoutError (408)":"TimeoutErrorRetries","RateLimitError (429)":"RateLimitErrorRetries","ContentPolicyViolationError (400)":"ContentPolicyViolationErrorRetries","InternalServerError (500)":"InternalServerErrorRetries"};var X=e=>{let{selectedModelGroup:l,setSelectedModelGroup:t,availableModelGroups:a,globalRetryPolicy:r,setGlobalRetryPolicy:i,defaultRetry:n,modelGroupRetryPolicy:o,setModelGroupRetryPolicy:d,handleSaveRetrySettings:c}=e;return(0,s.jsxs)(z.Z,{children:[(0,s.jsx)("div",{className:"flex items-center gap-4 mb-6",children:(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(D.Z,{children:"Retry Policy Scope:"}),(0,s.jsxs)(V.Z,{className:"ml-2 w-48",defaultValue:"global",value:"global"===l?"global":l||a[0],onValueChange:e=>t(e),children:[(0,s.jsx)(q.Z,{value:"global",children:"Global Default"}),a.map((e,l)=>(0,s.jsx)(q.Z,{value:e,onClick:()=>t(e),children:e},l))]})]})}),"global"===l?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(W.Z,{children:"Global Retry Policy"}),(0,s.jsx)(D.Z,{className:"mb-6",children:"Default retry settings applied to all model groups unless overridden"})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)(W.Z,{children:["Retry Policy for ",l]}),(0,s.jsx)(D.Z,{className:"mb-6",children:"Model-specific retry settings. Falls back to global defaults if not set."})]}),$&&(0,s.jsx)("table",{children:(0,s.jsx)("tbody",{children:Object.entries($).map((e,t)=>{var a,c,m,u;let h,[x,p]=e;if("global"===l)h=null!==(a=null==r?void 0:r[p])&&void 0!==a?a:n;else{let e=null==o?void 0:null===(c=o[l])||void 0===c?void 0:c[p];h=null!=e?e:null!==(m=null==r?void 0:r[p])&&void 0!==m?m:n}return(0,s.jsxs)("tr",{className:"flex justify-between items-center mt-2",children:[(0,s.jsxs)("td",{children:[(0,s.jsx)(D.Z,{children:x}),"global"!==l&&(0,s.jsxs)(D.Z,{className:"text-xs text-gray-500 ml-2",children:["(Global: ",null!==(u=null==r?void 0:r[p])&&void 0!==u?u:n,")"]})]}),(0,s.jsx)("td",{children:(0,s.jsx)(Y.Z,{className:"ml-5",value:h,min:0,step:1,onChange:e=>{"global"===l?i(l=>null==e?l:{...null!=l?l:{},[p]:e}):d(t=>{var s;let a=null!==(s=null==t?void 0:t[l])&&void 0!==s?s:{};return{...null!=t?t:{},[l]:{...a,[p]:e}}})}})})]},t)})})}),(0,s.jsx)(E.Z,{className:"mt-6 mr-8",onClick:c,children:"Save"})]})},Q=t(57840),ee=t(58760),el=t(867),et=t(5945),es=t(3810),ea=t(22116),er=t(89245),ei=t(5540),en=t(8881),eo=t(9114);let{Text:ed}=Q.default;var ec=e=>{let{accessToken:l,onReloadSuccess:t,buttonText:r="Reload Price Data",showIcon:i=!0,size:n="middle",type:o="primary",className:d=""}=e,[c,m]=(0,f.useState)(!1),[u,h]=(0,f.useState)(!1),[x,p]=(0,f.useState)(!1),[g,j]=(0,f.useState)(!1),[v,b]=(0,f.useState)(6),[y,N]=(0,f.useState)(null),[w,Z]=(0,f.useState)(!1);(0,f.useEffect)(()=>{C();let e=setInterval(()=>{C()},3e4);return()=>clearInterval(e)},[l]);let C=async()=>{if(l){Z(!0);try{console.log("Fetching reload status...");let e=await (0,a.getModelCostMapReloadStatus)(l);console.log("Received status:",e),N(e)}catch(e){console.error("Failed to fetch reload status:",e),N({scheduled:!1,interval_hours:null,last_run:null,next_run:null})}finally{Z(!1)}}},k=async()=>{if(!l){eo.Z.fromBackend("No access token available");return}m(!0);try{let e=await (0,a.reloadModelCostMap)(l);"success"===e.status?(eo.Z.success("Price data reloaded successfully! ".concat(e.models_count||0," models updated.")),null==t||t(),await C()):eo.Z.fromBackend("Failed to reload price data")}catch(e){console.error("Error reloading price data:",e),eo.Z.fromBackend("Failed to reload price data. Please try again.")}finally{m(!1)}},S=async()=>{if(!l){eo.Z.fromBackend("No access token available");return}if(v<=0){eo.Z.fromBackend("Hours must be greater than 0");return}h(!0);try{let e=await (0,a.scheduleModelCostMapReload)(l,v);"success"===e.status?(eo.Z.success("Periodic reload scheduled for every ".concat(v," hours")),j(!1),await C()):eo.Z.fromBackend("Failed to schedule periodic reload")}catch(e){console.error("Error scheduling reload:",e),eo.Z.fromBackend("Failed to schedule periodic reload. Please try again.")}finally{h(!1)}},A=async()=>{if(!l){eo.Z.fromBackend("No access token available");return}p(!0);try{let e=await (0,a.cancelModelCostMapReload)(l);"success"===e.status?(eo.Z.success("Periodic reload cancelled successfully"),await C()):eo.Z.fromBackend("Failed to cancel periodic reload")}catch(e){console.error("Error cancelling reload:",e),eo.Z.fromBackend("Failed to cancel periodic reload. Please try again.")}finally{p(!1)}},E=e=>{if(!e)return"Never";try{return new Date(e).toLocaleString()}catch(l){return e}};return(0,s.jsxs)("div",{className:d,children:[(0,s.jsxs)(ee.Z,{direction:"horizontal",size:"middle",style:{marginBottom:16},children:[(0,s.jsx)(el.Z,{title:"Hard Refresh Price Data",description:"This will immediately fetch the latest pricing information from the remote source. Continue?",onConfirm:k,okText:"Yes",cancelText:"No",okButtonProps:{style:{backgroundColor:"#6366f1",borderColor:"#6366f1",color:"white",fontWeight:"500",borderRadius:"0.375rem",padding:"0.375rem 0.75rem",height:"auto",fontSize:"0.875rem",lineHeight:"1.25rem",transition:"all 0.2s ease-in-out"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#4f46e5"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#6366f1"}},children:(0,s.jsx)(_.ZP,{type:o,size:n,loading:c,icon:i?(0,s.jsx)(er.Z,{}):void 0,style:{backgroundColor:"#6366f1",borderColor:"#6366f1",color:"white",fontWeight:"500",borderRadius:"0.375rem",padding:"0.375rem 0.75rem",height:"auto",fontSize:"0.875rem",lineHeight:"1.25rem",transition:"all 0.2s ease-in-out"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#4f46e5"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#6366f1"},children:r})}),(null==y?void 0:y.scheduled)?(0,s.jsx)(_.ZP,{type:"default",size:n,danger:!0,icon:(0,s.jsx)(en.Z,{}),loading:x,onClick:A,style:{borderColor:"#ff4d4f",color:"#ff4d4f",fontWeight:"500",borderRadius:"0.375rem",padding:"0.375rem 0.75rem",height:"auto",fontSize:"0.875rem",lineHeight:"1.25rem"},children:"Cancel Periodic Reload"}):(0,s.jsx)(_.ZP,{type:"default",size:n,icon:(0,s.jsx)(ei.Z,{}),onClick:()=>j(!0),style:{borderColor:"#d9d9d9",color:"#6366f1",fontWeight:"500",borderRadius:"0.375rem",padding:"0.375rem 0.75rem",height:"auto",fontSize:"0.875rem",lineHeight:"1.25rem"},children:"Set Up Periodic Reload"})]}),y&&(0,s.jsx)(et.Z,{size:"small",style:{backgroundColor:"#f8f9fa",border:"1px solid #e9ecef",borderRadius:8},children:(0,s.jsxs)(ee.Z,{direction:"vertical",size:"small",style:{width:"100%"},children:[y.scheduled?(0,s.jsx)("div",{children:(0,s.jsxs)(es.Z,{color:"green",icon:(0,s.jsx)(ei.Z,{}),children:["Scheduled every ",y.interval_hours," hours"]})}):(0,s.jsx)(ed,{type:"secondary",children:"No periodic reload scheduled"}),(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsx)(ed,{type:"secondary",style:{fontSize:"12px"},children:"Last run:"}),(0,s.jsx)(ed,{style:{fontSize:"12px"},children:E(y.last_run)})]}),y.scheduled&&(0,s.jsxs)(s.Fragment,{children:[y.next_run&&(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsx)(ed,{type:"secondary",style:{fontSize:"12px"},children:"Next run:"}),(0,s.jsx)(ed,{style:{fontSize:"12px"},children:E(y.next_run)})]}),(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsx)(ed,{type:"secondary",style:{fontSize:"12px"},children:"Status:"}),(0,s.jsx)(es.Z,{color:(null==y?void 0:y.scheduled)?y.last_run?"success":"processing":"default",children:(null==y?void 0:y.scheduled)?y.last_run?"Active":"Ready":"Not scheduled"})]})]})]})}),(0,s.jsxs)(ea.Z,{title:"Set Up Periodic Reload",open:g,onOk:S,onCancel:()=>j(!1),confirmLoading:u,okText:"Schedule",cancelText:"Cancel",okButtonProps:{style:{backgroundColor:"#6366f1",borderColor:"#6366f1",color:"white"}},children:[(0,s.jsx)("div",{style:{marginBottom:16},children:(0,s.jsx)(ed,{children:"Set up automatic reload of price data every:"})}),(0,s.jsx)("div",{style:{marginBottom:16},children:(0,s.jsx)(Y.Z,{min:1,max:168,value:v,onChange:e=>b(e||6),addonAfter:"hours",style:{width:"100%"}})}),(0,s.jsx)("div",{children:(0,s.jsxs)(ed,{type:"secondary",children:["This will automatically fetch the latest pricing data from the remote source every ",v," hours."]})})]})]})},em=()=>{let{accessToken:e}=(0,n.Z)(),{refetch:l}=m();return(0,s.jsx)(z.Z,{children:(0,s.jsxs)("div",{className:"p-6",children:[(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsx)(W.Z,{children:"Price Data Management"}),(0,s.jsx)(D.Z,{className:"text-tremor-content",children:"Manage model pricing data and configure automatic reload schedules"})]}),(0,s.jsx)(ec,{accessToken:e,onReloadSuccess:()=>{l()},buttonText:"Reload Price Data",size:"middle",type:"primary",className:"w-full"})]})})};let eu=async(e,l,t)=>{try{var s,a;console.log("handling submit for formValues:",e);let l=e.model_mappings||[];if("model_mappings"in e&&delete e.model_mappings,e.model&&e.model.includes("all-wildcard")){let t=e.custom_llm_provider,a=(null!==(s=L.fK[t])&&void 0!==s?s:t.toLowerCase())+"/*";e.model_name=a,l.push({public_name:a,litellm_model:a}),e.model=a}let t=[];for(let s of l){let l={},r={},i=s.public_name;for(let[t,i]of(l.model=s.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),l.model=s.litellm_model,console.log("formValues add deployment:",e),Object.entries(e)))if(""!==i&&"custom_pricing"!==t&&"pricing_model"!==t&&"cache_control"!==t){if("model_name"==t)l.model=i;else if("custom_llm_provider"==t){console.log("custom_llm_provider:",i);let e=null!==(a=L.fK[i])&&void 0!==a?a:i.toLowerCase();l.custom_llm_provider=e,console.log("custom_llm_provider mappingResult:",e)}else if("model"==t)continue;else if("base_model"===t)r[t]=i;else if("team_id"===t)r.team_id=i;else if("model_access_group"===t)r.access_groups=i;else if("mode"==t)console.log("placing mode in modelInfo"),r.mode=i,delete l.mode;else if("custom_model_name"===t)l.model=i;else if("litellm_extra_params"==t){console.log("litellm_extra_params:",i);let e={};if(i&&void 0!=i){try{e=JSON.parse(i)}catch(e){throw eo.Z.fromBackend("Failed to parse LiteLLM Extra Params: "+e),Error("Failed to parse litellm_extra_params: "+e)}for(let[t,s]of Object.entries(e))l[t]=s}}else if("model_info_params"==t){console.log("model_info_params:",i);let e={};if(i&&void 0!=i){try{e=JSON.parse(i)}catch(e){throw eo.Z.fromBackend("Failed to parse LiteLLM Extra Params: "+e),Error("Failed to parse litellm_extra_params: "+e)}for(let[l,t]of Object.entries(e))r[l]=t}}else if("input_cost_per_token"===t||"output_cost_per_token"===t||"input_cost_per_second"===t){i&&(l[t]=Number(i));continue}else l[t]=i}t.push({litellmParamsObj:l,modelInfoObj:r,modelName:i})}return t}catch(e){eo.Z.fromBackend("Failed to create model: "+e)}},eh=async(e,l,t,s)=>{try{let r=await eu(e,l,t);if(!r||0===r.length)return;for(let e of r){let{litellmParamsObj:t,modelInfoObj:s,modelName:r}=e,i={model_name:r,litellm_params:t,model_info:s},n=await (0,a.modelCreateCall)(l,i);console.log("response for model create call: ".concat(n.data))}s&&s(),t.resetFields()}catch(e){eo.Z.fromBackend("Failed to add model: "+e)}};var ex=t(53410),ep=t(62490),eg=t(10032),ef=t(21609),ej=t(31283),ev=t(37592);let e_=(0,i.n)("providerFields"),eb=()=>(0,r.a)({queryKey:e_.list({}),queryFn:async()=>await (0,a.getProviderCreateMetadata)(),staleTime:864e5,gcTime:864e5});var ey=t(3632),eN=t(56522),ew=t(47451),eZ=t(69410),eC=t(65319),ek=t(4260);let{Link:eS}=Q.default,eA=e=>{var l,t,s,a,r;let i="password"===e.field_type?"password":"select"===e.field_type?"select":"upload"===e.field_type?"upload":"textarea"===e.field_type?"textarea":"text";return{key:e.key,label:e.label,placeholder:null!==(l=e.placeholder)&&void 0!==l?l:void 0,tooltip:null!==(t=e.tooltip)&&void 0!==t?t:void 0,required:null!==(s=e.required)&&void 0!==s&&s,type:i,options:null!==(a=e.options)&&void 0!==a?a:void 0,defaultValue:null!==(r=e.default_value)&&void 0!==r?r:void 0}},eE={};var eP=e=>{let{selectedProvider:l,uploadProps:t}=e,a=L.Cl[l],r=eg.Z.useFormInstance(),{data:i,isLoading:n,error:o}=eb(),d=f.useMemo(()=>{if(!i)return null;let e={};return i.forEach(l=>{let t=l.provider_display_name,s=l.credential_fields.map(eA);e[t]=s,l.provider&&(e[l.provider]=s),l.litellm_provider&&(e[l.litellm_provider]=s)}),e},[i]);f.useEffect(()=>{d&&Object.assign(eE,d)},[d]);let c=f.useMemo(()=>{var e;let t=null!==(e=eE[a])&&void 0!==e?e:eE[l];if(t)return t;if(!i)return[];let s=i.find(e=>e.provider_display_name===a||e.provider===l||e.litellm_provider===l);if(!s)return[];let r=s.credential_fields.map(eA);return eE[s.provider_display_name]=r,s.provider&&(eE[s.provider]=r),s.litellm_provider&&(eE[s.litellm_provider]=r),r},[a,l,i]),m={name:"file",accept:".json",beforeUpload:e=>{if("application/json"===e.type){let l=new FileReader;l.onload=e=>{if(e.target){let l=e.target.result;console.log("Setting field value from JSON, length: ".concat(l.length)),r.setFieldsValue({vertex_credentials:l}),console.log("Form values after setting:",r.getFieldsValue())}},l.readAsText(e)}return!1},onChange(e){console.log("Upload onChange triggered in ProviderSpecificFields"),console.log("Current form values:",r.getFieldsValue()),"uploading"!==e.file.status&&console.log(e.file,e.fileList)}};return(0,s.jsxs)(s.Fragment,{children:[n&&0===c.length&&(0,s.jsx)(ew.Z,{children:(0,s.jsx)(eZ.Z,{span:24,children:(0,s.jsx)(eN.x,{className:"mb-2",children:"Loading provider fields..."})})}),o&&0===c.length&&(0,s.jsx)(ew.Z,{children:(0,s.jsx)(eZ.Z,{span:24,children:(0,s.jsx)(eN.x,{className:"mb-2 text-red-500",children:o instanceof Error?o.message:"Failed to load provider credential fields"})})}),c.map(e=>{var l;return(0,s.jsxs)(f.Fragment,{children:[(0,s.jsx)(eg.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,s.jsx)(ev.default,{placeholder:e.placeholder,defaultValue:e.defaultValue,children:null===(l=e.options)||void 0===l?void 0:l.map(e=>(0,s.jsx)(ev.default.Option,{value:e,children:e},e))}):"upload"===e.type?(0,s.jsx)(eC.default,{...m,onChange:l=>{(null==t?void 0:t.onChange)&&t.onChange(l),setTimeout(()=>{let l=r.getFieldValue(e.key);console.log("".concat(e.key," value after upload:"),JSON.stringify(l))},500)},children:(0,s.jsx)(_.ZP,{icon:(0,s.jsx)(ey.Z,{}),children:"Click to Upload"})}):"textarea"===e.type?(0,s.jsx)(ek.default.TextArea,{placeholder:e.placeholder,defaultValue:e.defaultValue,rows:6,style:{fontFamily:"monospace",fontSize:"12px"}}):(0,s.jsx)(eN.o,{placeholder:e.placeholder,type:"password"===e.type?"password":"text",defaultValue:e.defaultValue})}),"vertex_credentials"===e.key&&(0,s.jsx)(ew.Z,{children:(0,s.jsx)(eZ.Z,{children:(0,s.jsx)(eN.x,{className:"mb-3 mt-1",children:"Give a gcp service account(.json file)"})})}),"base_model"===e.key&&(0,s.jsxs)(ew.Z,{children:[(0,s.jsx)(eZ.Z,{span:10}),(0,s.jsx)(eZ.Z,{span:10,children:(0,s.jsxs)(eN.x,{className:"mb-2",children:["The actual model your azure deployment uses. Used for accurate cost tracking. Select name from"," ",(0,s.jsx)(eS,{href:"https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json",target:"_blank",children:"here"})]})})]})]},e.key)})]})};let{Link:eM}=Q.default;var eL=e=>{let{open:l,onCancel:t,onAddCredential:a,uploadProps:r}=e,[i]=eg.Z.useForm(),[n,o]=(0,f.useState)(L.Cl.OpenAI);return(0,s.jsx)(ea.Z,{title:"Add New Credential",open:l,onCancel:()=>{t(),i.resetFields()},footer:null,width:600,children:(0,s.jsxs)(eg.Z,{form:i,onFinish:e=>{a(Object.entries(e).reduce((e,l)=>{let[t,s]=l;return""!==s&&null!=s&&(e[t]=s),e},{})),i.resetFields()},layout:"vertical",children:[(0,s.jsx)(eg.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],children:(0,s.jsx)(ej.o,{placeholder:"Enter a friendly name for these credentials"})}),(0,s.jsx)(eg.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,s.jsx)(ev.default,{showSearch:!0,onChange:e=>{o(e),i.setFieldValue("custom_llm_provider",e)},children:Object.entries(L.Cl).map(e=>{let[l,t]=e;return(0,s.jsx)(ev.default.Option,{value:l,children:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("img",{src:L.cd[t],alt:"".concat(l," logo"),className:"w-5 h-5",onError:e=>{let l=e.target,s=l.parentElement;if(s){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=t.charAt(0),s.replaceChild(e,l)}}}),(0,s.jsx)("span",{children:t})]})},l)})})}),(0,s.jsx)(eP,{selectedProvider:n,uploadProps:r}),(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(M.Z,{title:"Get help on our github",children:(0,s.jsx)(eM,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(_.ZP,{onClick:()=>{t(),i.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,s.jsx)(_.ZP,{htmlType:"submit",children:"Add Credential"})]})]})]})})};let{Link:eF}=Q.default;function eI(e){let{open:l,onCancel:t,onUpdateCredential:a,uploadProps:r,existingCredential:i}=e,[n]=eg.Z.useForm(),[o,d]=(0,f.useState)(L.Cl.Anthropic);return(0,f.useEffect)(()=>{if(i){let e=Object.entries(i.credential_values||{}).reduce((e,l)=>{let[t,s]=l;return e[t]=null!=s?s:null,e},{});n.setFieldsValue({credential_name:i.credential_name,custom_llm_provider:i.credential_info.custom_llm_provider,...e}),d(i.credential_info.custom_llm_provider)}},[i]),(0,s.jsx)(ea.Z,{title:"Edit Credential",open:l,onCancel:()=>{t(),n.resetFields()},footer:null,width:600,destroyOnHidden:!0,children:(0,s.jsxs)(eg.Z,{form:n,onFinish:e=>{a(Object.entries(e).reduce((e,l)=>{let[t,s]=l;return""!==s&&null!=s&&(e[t]=s),e},{})),n.resetFields()},layout:"vertical",children:[(0,s.jsx)(eg.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==i?void 0:i.credential_name,children:(0,s.jsx)(ej.o,{placeholder:"Enter a friendly name for these credentials",disabled:null!=i&&!!i.credential_name})}),(0,s.jsx)(eg.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,s.jsx)(ev.default,{showSearch:!0,onChange:e=>{d(e),n.setFieldValue("custom_llm_provider",e)},children:Object.entries(L.Cl).map(e=>{let[l,t]=e;return(0,s.jsx)(ev.default.Option,{value:l,children:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("img",{src:L.cd[t],alt:"".concat(l," logo"),className:"w-5 h-5",onError:e=>{let l=e.target,s=l.parentElement;if(s){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=t.charAt(0),s.replaceChild(e,l)}}}),(0,s.jsx)("span",{children:t})]})},l)})})}),(0,s.jsx)(eP,{selectedProvider:o,uploadProps:r}),(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(M.Z,{title:"Get help on our github",children:(0,s.jsx)(eF,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(_.ZP,{onClick:()=>{t(),n.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,s.jsx)(_.ZP,{htmlType:"submit",children:"Update Credential"})]})]})]})})}var eT=e=>{var l;let{uploadProps:t}=e,{accessToken:r}=(0,n.Z)(),{data:i,refetch:o}=d(),c=(null==i?void 0:i.credentials)||[],[m,u]=(0,f.useState)(!1),[h,x]=(0,f.useState)(!1),[p,g]=(0,f.useState)(null),[j,v]=(0,f.useState)(null),[_,b]=(0,f.useState)(!1),[y,N]=(0,f.useState)(!1),[w]=eg.Z.useForm(),Z=["credential_name","custom_llm_provider"],C=async e=>{if(!r)return;let l=Object.entries(e).filter(e=>{let[l]=e;return!Z.includes(l)}).reduce((e,l)=>{let[t,s]=l;return{...e,[t]:s}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}};await (0,a.credentialUpdateCall)(r,e.credential_name,t),eo.Z.success("Credential updated successfully"),x(!1),await o()},k=async e=>{if(!r)return;let l=Object.entries(e).filter(e=>{let[l]=e;return!Z.includes(l)}).reduce((e,l)=>{let[t,s]=l;return{...e,[t]:s}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}};await (0,a.credentialCreateCall)(r,t),eo.Z.success("Credential added successfully"),u(!1),await o()},A=e=>{let l={openai:"blue",azure:"indigo",anthropic:"purple",default:"gray"},t=l[e.toLowerCase()]||l.default;return(0,s.jsx)(ep.Ct,{color:t,size:"xs",children:e})},E=async()=>{if(r&&j){N(!0);try{await (0,a.credentialDeleteCall)(r,j.credential_name),eo.Z.success("Credential deleted successfully"),await o()}catch(e){eo.Z.error("Failed to delete credential")}finally{v(null),b(!1),N(!1)}}},P=e=>{v(e),b(!0)};return(0,s.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto p-2",children:[(0,s.jsx)(ep.zx,{onClick:()=>u(!0),children:"Add Credential"}),(0,s.jsx)("div",{className:"flex justify-between items-center mt-4 mb-4",children:(0,s.jsx)(ep.xv,{children:"Configured credentials for different AI providers. Add and manage your API credentials."})}),(0,s.jsx)(ep.Zb,{children:(0,s.jsxs)(ep.iA,{children:[(0,s.jsx)(ep.ss,{children:(0,s.jsxs)(ep.SC,{children:[(0,s.jsx)(ep.xs,{children:"Credential Name"}),(0,s.jsx)(ep.xs,{children:"Provider"}),(0,s.jsx)(ep.xs,{children:"Actions"})]})}),(0,s.jsx)(ep.RM,{children:c&&0!==c.length?c.map((e,l)=>{var t;return(0,s.jsxs)(ep.SC,{children:[(0,s.jsx)(ep.pj,{children:e.credential_name}),(0,s.jsx)(ep.pj,{children:A((null===(t=e.credential_info)||void 0===t?void 0:t.custom_llm_provider)||"-")}),(0,s.jsxs)(ep.pj,{children:[(0,s.jsx)(ep.zx,{icon:ex.Z,variant:"light",size:"sm",onClick:()=>{g(e),x(!0)}}),(0,s.jsx)(ep.zx,{icon:S.Z,variant:"light",size:"sm",onClick:()=>P(e),className:"ml-2"})]})]},l)}):(0,s.jsx)(ep.SC,{children:(0,s.jsx)(ep.pj,{colSpan:4,className:"text-center py-4 text-gray-500",children:"No credentials configured"})})})]})}),m&&(0,s.jsx)(eL,{onAddCredential:k,open:m,onCancel:()=>u(!1),uploadProps:t}),h&&(0,s.jsx)(eI,{open:h,existingCredential:p,onUpdateCredential:C,uploadProps:t,onCancel:()=>x(!1)}),(0,s.jsx)(ef.Z,{isOpen:_,onCancel:()=>{v(null),b(!1)},onOk:E,title:"Delete Credential?",message:"Are you sure you want to delete this credential? This action cannot be undone and may break existing integrations.",resourceInformationTitle:"Credential Information",resourceInformation:[{label:"Credential Name",value:null==j?void 0:j.credential_name},{label:"Provider",value:(null==j?void 0:null===(l=j.credential_info)||void 0===l?void 0:l.custom_llm_provider)||"-"}],confirmLoading:y,requiredConfirmation:null==j?void 0:j.credential_name})]})},eR=t(20347),eO=t(23628),eV=t(29827),eq=t(49804),ez=t(12485),eD=t(18135),eB=t(35242),eG=t(77991),eU=t(34419),eH=t(58643),eK=t(29),eJ=t.n(eK),eW=t(23496),eY=t(35291),e$=t(23639);let{Text:eX}=Q.default;var eQ=e=>{let{formValues:l,accessToken:t,testMode:r,modelName:i="this model",onClose:n,onTestComplete:o}=e,[d,c]=f.useState(null),[m,u]=f.useState(null),[h,x]=f.useState(null),[p,g]=f.useState(!0),[j,v]=f.useState(!1),[b,y]=f.useState(!1),N=async()=>{g(!0),y(!1),c(null),u(null),x(null),v(!1),await new Promise(e=>setTimeout(e,100));try{console.log("Testing connection with form values:",l);let r=await eu(l,t,null);if(!r){console.log("No result from prepareModelAddRequest"),c("Failed to prepare model data. Please check your form inputs."),v(!1),g(!1);return}console.log("Result from prepareModelAddRequest:",r);let{litellmParamsObj:i,modelInfoObj:n,modelName:o}=r[0],d=await (0,a.testConnectionRequest)(t,i,n,null==n?void 0:n.mode);if("success"===d.status)eo.Z.success("Connection test successful!"),c(null),v(!0);else{var e,s;let l=(null===(e=d.result)||void 0===e?void 0:e.error)||d.message||"Unknown error";c(l),u(i),x(null===(s=d.result)||void 0===s?void 0:s.raw_request_typed_dict),v(!1)}}catch(e){console.error("Test connection error:",e),c(e instanceof Error?e.message:String(e)),v(!1)}finally{g(!1),o&&o()}};f.useEffect(()=>{let e=setTimeout(()=>{N()},200);return()=>clearTimeout(e)},[]);let w=e=>e?e.split("stack trace:")[0].trim().replace(/^litellm\.(.*?)Error: /,""):"Unknown error",Z="string"==typeof d?w(d):(null==d?void 0:d.message)?w(d.message):"Unknown error",C=h?((e,l,t)=>{let s=JSON.stringify(l,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(t).map(e=>{let[l,t]=e;return"-H '".concat(l,": ").concat(t,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(s,"\n }'")})(h.raw_request_api_base,h.raw_request_body,h.raw_request_headers||{}):"";return(0,s.jsxs)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:[p?(0,s.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},className:"jsx-dc9a0e2d897fe63b",children:[(0,s.jsx)("div",{style:{marginBottom:"16px"},className:"jsx-dc9a0e2d897fe63b loading-spinner",children:(0,s.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-dc9a0e2d897fe63b"})}),(0,s.jsxs)(eX,{style:{fontSize:"16px"},children:["Testing connection to ",i,"..."]}),(0,s.jsx)(eJ(),{id:"dc9a0e2d897fe63b",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,s.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"32px 20px"},children:[(0,s.jsx)("div",{style:{color:"#52c41a",fontSize:"24px",display:"flex",alignItems:"center"},children:(0,s.jsx)("svg",{viewBox:"64 64 896 896",focusable:"false","data-icon":"check-circle",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",children:(0,s.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,s.jsxs)(eX,{type:"success",style:{fontSize:"18px",fontWeight:500,marginLeft:"10px"},children:["Connection to ",i," successful!"]})]}):(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",marginBottom:"20px"},children:[(0,s.jsx)(eY.Z,{style:{color:"#ff4d4f",fontSize:"24px",marginRight:"12px"}}),(0,s.jsxs)(eX,{type:"danger",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",i," failed"]})]}),(0,s.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,s.jsxs)(eX,{strong:!0,style:{display:"block",marginBottom:"8px"},children:["Error:"," "]}),(0,s.jsx)(eX,{type:"danger",style:{fontSize:"14px",lineHeight:"1.5"},children:Z}),d&&(0,s.jsx)("div",{style:{marginTop:"12px"},children:(0,s.jsx)(_.ZP,{type:"link",onClick:()=>y(!b),style:{paddingLeft:0,height:"auto"},children:b?"Hide Details":"Show Details"})})]}),b&&(0,s.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,s.jsx)(eX,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"Troubleshooting Details"}),(0,s.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 d?d:JSON.stringify(d,null,2)})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(eX,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"API Request"}),(0,s.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"250px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:C||"No request data available"}),(0,s.jsx)(_.ZP,{style:{marginTop:"8px"},icon:(0,s.jsx)(e$.Z,{}),onClick:()=>{navigator.clipboard.writeText(C||""),eo.Z.success("Copied to clipboard")},children:"Copy to Clipboard"})]})]})}),(0,s.jsx)(eW.Z,{style:{margin:"24px 0 16px"}}),(0,s.jsx)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:(0,s.jsx)(_.ZP,{type:"link",href:"https://docs.litellm.ai/docs/providers",target:"_blank",icon:(0,s.jsx)(R.Z,{}),children:"View Documentation"})})]})};let e0=async(e,l,t,s)=>{try{console.log("=== AUTO ROUTER SUBMIT HANDLER CALLED ==="),console.log("handling auto router submit for formValues:",e),console.log("Access token:",l?"Present":"Missing"),console.log("Form:",t?"Present":"Missing"),console.log("Callback:",s?"Present":"Missing");let r={model_name:e.auto_router_name,litellm_params:{model:"auto_router/".concat(e.auto_router_name),auto_router_config:JSON.stringify(e.auto_router_config),auto_router_default_model:e.auto_router_default_model},model_info:{}};e.auto_router_embedding_model&&"custom"!==e.auto_router_embedding_model?r.litellm_params.auto_router_embedding_model=e.auto_router_embedding_model:e.custom_embedding_model&&(r.litellm_params.auto_router_embedding_model=e.custom_embedding_model),e.team_id&&(r.model_info.team_id=e.team_id),e.model_access_group&&e.model_access_group.length>0&&(r.model_info.access_groups=e.model_access_group),console.log("Auto router configuration to be created:",r),console.log("Auto router config (stringified):",r.litellm_params.auto_router_config),console.log("Calling modelCreateCall with:",{accessToken:l?"Present":"Missing",config:r});let i=await (0,a.modelCreateCall)(l,r);console.log("response for auto router create call:",i),t.resetFields()}catch(e){console.error("Failed to add auto router:",e),eo.Z.fromBackend("Failed to add auto router: "+e)}};var e1=t(10703),e2=t(44851),e4=t(96473),e5=t(70464),e6=t(26349),e3=t(92280);let{TextArea:e8}=ek.default,{Panel:e7}=e2.default;var e9=e=>{let{modelInfo:l,value:t,onChange:a}=e,[r,i]=(0,f.useState)([]),[n,o]=(0,f.useState)(!1),[d,c]=(0,f.useState)([]);(0,f.useEffect)(()=>{if(null==t?void 0:t.routes){let e=t.routes.map((e,l)=>({id:e.id||"route-".concat(l,"-").concat(Date.now()),model:e.name||e.model||"",utterances:e.utterances||[],description:e.description||"",score_threshold:e.score_threshold||.5}));i(e),c(e.map(e=>e.id))}else i([]),c([])},[t]);let m=e=>{let l=r.filter(l=>l.id!==e);i(l),h(l),c(l=>l.filter(l=>l!==e))},u=(e,l,t)=>{let s=r.map(s=>s.id===e?{...s,[l]:t}:s);i(s),h(s)},h=e=>{let l={routes:e.map(e=>({name:e.model,utterances:e.utterances,description:e.description,score_threshold:e.score_threshold}))};null==a||a(l)},x=l.map(e=>({value:e.model_group,label:e.model_group}));return(0,s.jsxs)("div",{className:"w-full max-w-none",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-6 w-full",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(e3.x,{className:"text-lg font-semibold",children:"Routes Configuration"}),(0,s.jsx)(M.Z,{title:"Configure routing logic to automatically select the best model based on user input patterns",children:(0,s.jsx)(R.Z,{className:"text-gray-400"})})]}),(0,s.jsx)(_.ZP,{type:"primary",icon:(0,s.jsx)(e4.Z,{}),onClick:()=>{let e="route-".concat(Date.now()),l=[...r,{id:e,model:"",utterances:[],description:"",score_threshold:.5}];i(l),h(l),c(l=>[...l,e])},className:"bg-blue-600 hover:bg-blue-700",children:"Add Route"})]}),0===r.length?(0,s.jsx)("div",{className:"text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200 mb-6",children:(0,s.jsx)(e3.x,{children:"No routes configured. Click “Add Route” to get started."})}):(0,s.jsx)("div",{className:"space-y-3 mb-6 w-full",children:r.map((e,l)=>(0,s.jsx)(et.Z,{className:"border border-gray-200 shadow-sm w-full",bodyStyle:{padding:0},children:(0,s.jsx)(e2.default,{ghost:!0,expandIcon:e=>{let{isActive:l}=e;return(0,s.jsx)(e5.Z,{rotate:l?180:0})},activeKey:d,onChange:e=>c(Array.isArray(e)?e:[e].filter(Boolean)),items:[{key:e.id,label:(0,s.jsxs)("div",{className:"flex justify-between items-center py-2",children:[(0,s.jsxs)(e3.x,{className:"font-medium text-base",children:["Route ",l+1,": ",e.model||"Unnamed"]}),(0,s.jsx)(_.ZP,{type:"text",danger:!0,icon:(0,s.jsx)(e6.Z,{}),onClick:l=>{l.stopPropagation(),m(e.id)},className:"mr-2"})]}),children:(0,s.jsxs)("div",{className:"px-6 pb-6 w-full",children:[(0,s.jsxs)("div",{className:"mb-4 w-full",children:[(0,s.jsx)(e3.x,{className:"text-sm font-medium mb-2 block",children:"Model"}),(0,s.jsx)(ev.default,{value:e.model,onChange:l=>u(e.id,"model",l),placeholder:"Select model",showSearch:!0,style:{width:"100%"},options:x})]}),(0,s.jsxs)("div",{className:"mb-4 w-full",children:[(0,s.jsx)(e3.x,{className:"text-sm font-medium mb-2 block",children:"Description"}),(0,s.jsx)(e8,{value:e.description,onChange:l=>u(e.id,"description",l.target.value),placeholder:"Describe when this route should be used...",rows:2,style:{width:"100%"}})]}),(0,s.jsxs)("div",{className:"mb-4 w-full",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,s.jsx)(e3.x,{className:"text-sm font-medium",children:"Score Threshold"}),(0,s.jsx)(M.Z,{title:"Minimum similarity score to route to this model (0-1)",children:(0,s.jsx)(R.Z,{className:"text-gray-400"})})]}),(0,s.jsx)(Y.Z,{value:e.score_threshold,onChange:l=>u(e.id,"score_threshold",l||0),min:0,max:1,step:.1,style:{width:"100%"},placeholder:"0.5"})]}),(0,s.jsxs)("div",{className:"w-full",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,s.jsx)(e3.x,{className:"text-sm font-medium",children:"Example Utterances"}),(0,s.jsx)(M.Z,{title:"Training examples for this route. Type an utterance and press Enter to add it.",children:(0,s.jsx)(R.Z,{className:"text-gray-400"})})]}),(0,s.jsx)(e3.x,{className:"text-xs text-gray-500 mb-2",children:"Type an utterance and press Enter to add it. You can also paste multiple lines."}),(0,s.jsx)(ev.default,{mode:"tags",value:e.utterances,onChange:l=>u(e.id,"utterances",l),placeholder:"Type an utterance and press Enter...",style:{width:"100%"},tokenSeparators:["\n"],maxTagCount:"responsive",allowClear:!0})]})]})}]})},e.id))}),(0,s.jsxs)("div",{className:"border-t pt-6 w-full",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4 w-full",children:[(0,s.jsx)(e3.x,{className:"text-lg font-semibold",children:"JSON Preview"}),(0,s.jsx)(_.ZP,{type:"link",onClick:()=>o(!n),className:"text-blue-600 p-0",children:n?"Hide":"Show"})]}),n&&(0,s.jsx)(et.Z,{className:"bg-gray-50 w-full",children:(0,s.jsx)("pre",{className:"text-sm overflow-auto max-h-64 w-full",children:JSON.stringify({routes:r.map(e=>({name:e.model,utterances:e.utterances,description:e.description,score_threshold:e.score_threshold}))},null,2)})})]})]})};let{Title:le,Link:ll}=Q.default;var lt=e=>{let{form:l,handleOk:t,accessToken:r,userRole:i}=e,[n,o]=(0,f.useState)(!1),[d,c]=(0,f.useState)(!1),[m,u]=(0,f.useState)(""),[h,x]=(0,f.useState)([]),[p,g]=(0,f.useState)([]),[j,v]=(0,f.useState)(!1),[b,y]=(0,f.useState)(!1),[N,w]=(0,f.useState)(null);(0,f.useEffect)(()=>{(async()=>{x((await (0,a.modelAvailableCall)(r,"","",!1,null,!0,!0)).data.map(e=>e.id))})()},[r]),(0,f.useEffect)(()=>{(async()=>{try{let e=await (0,e1.p)(r);console.log("Fetched models for auto router:",e),g(e)}catch(e){console.error("Error fetching model info for auto router:",e)}})()},[r]);let Z=eR.ZL.includes(i),C=async()=>{c(!0),u("test-".concat(Date.now())),o(!0)},k=()=>{console.log("Auto router submit triggered!"),console.log("Router config:",N);let e=l.getFieldsValue();if(console.log("Form values:",e),!e.auto_router_name){eo.Z.fromBackend("Please enter an Auto Router Name");return}if(!e.auto_router_default_model){eo.Z.fromBackend("Please select a Default Model");return}if(l.setFieldsValue({custom_llm_provider:"auto_router",model:e.auto_router_name,api_key:"not_required_for_auto_router"}),!N||!N.routes||0===N.routes.length){eo.Z.fromBackend("Please configure at least one route for the auto router");return}if(N.routes.filter(e=>!e.name||!e.description||0===e.utterances.length).length>0){eo.Z.fromBackend("Please ensure all routes have a target model, description, and at least one utterance");return}l.validateFields().then(e=>{console.log("Form validation passed, submitting with values:",e);let s={...e,auto_router_config:N};console.log("Final submit values:",s),e0(s,r,l,t)}).catch(e=>{console.error("Validation failed:",e);let l=e.errorFields||[];if(l.length>0){let e=l.map(e=>{let l=e.name[0];return({auto_router_name:"Auto Router Name",auto_router_default_model:"Default Model",auto_router_embedding_model:"Embedding Model"})[l]||l});eo.Z.fromBackend("Please fill in the following required fields: ".concat(e.join(", ")))}else eo.Z.fromBackend("Please fill in all required fields")})};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(le,{level:2,children:"Add Auto Router"}),(0,s.jsx)(eN.x,{className:"text-gray-600 mb-6",children:"Create an auto router with intelligent routing logic that automatically selects the best model based on user input patterns and semantic matching."}),(0,s.jsx)(et.Z,{children:(0,s.jsxs)(eg.Z,{form:l,onFinish:k,labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(eg.Z.Item,{rules:[{required:!0,message:"Auto router name is required"}],label:"Auto Router Name",name:"auto_router_name",tooltip:"Unique name for this auto router configuration",labelCol:{span:10},labelAlign:"left",children:(0,s.jsx)(eN.o,{placeholder:"e.g., auto_router_1, smart_routing"})}),(0,s.jsx)("div",{className:"w-full mb-4",children:(0,s.jsx)(e9,{modelInfo:p,value:N,onChange:e=>{w(e),l.setFieldValue("auto_router_config",e)}})}),(0,s.jsx)(eg.Z.Item,{rules:[{required:!0,message:"Default model is required"}],label:"Default Model",name:"auto_router_default_model",tooltip:"Fallback model to use when auto routing logic cannot determine the best model",labelCol:{span:10},labelAlign:"left",children:(0,s.jsx)(ev.default,{placeholder:"Select a default model",onChange:e=>{v("custom"===e)},options:[...Array.from(new Set(p.map(e=>e.model_group))).map(e=>({value:e,label:e})),{value:"custom",label:"Enter custom model name"}],style:{width:"100%"},showSearch:!0})}),(0,s.jsx)(eg.Z.Item,{label:"Embedding Model",name:"auto_router_embedding_model",tooltip:"Optional: Embedding model to use for semantic routing decisions",labelCol:{span:10},labelAlign:"left",children:(0,s.jsx)(ev.default,{value:l.getFieldValue("auto_router_embedding_model"),placeholder:"Select an embedding model (optional)",onChange:e=>{y("custom"===e),l.setFieldValue("auto_router_embedding_model",e)},options:[...Array.from(new Set(p.map(e=>e.model_group))).map(e=>({value:e,label:e})),{value:"custom",label:"Enter custom model name"}],style:{width:"100%"},showSearch:!0,allowClear:!0})}),(0,s.jsxs)("div",{className:"flex items-center my-4",children:[(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,s.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Additional Settings"}),(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),Z&&(0,s.jsx)(eg.Z.Item,{label:"Model Access Group",name:"model_access_group",className:"mb-4",tooltip:"Use model access groups to control who can access this auto router",children:(0,s.jsx)(ev.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],options:h.map(e=>({value:e,label:e})),maxTagCount:"responsive",allowClear:!0})}),(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,s.jsx)(M.Z,{title:"Get help on our github",children:(0,s.jsx)(Q.default.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{className:"space-x-2",children:[(0,s.jsx)(_.ZP,{onClick:C,loading:d,children:"Test Connect"}),(0,s.jsx)(_.ZP,{onClick:()=>{console.log("Add Auto Router button clicked!"),console.log("Current router config:",N),console.log("Current form values:",l.getFieldsValue()),k()},children:"Add Auto Router"})]})]})]})}),(0,s.jsx)(ea.Z,{title:"Connection Test Results",open:n,onCancel:()=>{o(!1),c(!1)},footer:[(0,s.jsx)(_.ZP,{onClick:()=>{o(!1),c(!1)},children:"Close"},"close")],width:700,children:n&&(0,s.jsx)(eQ,{formValues:l.getFieldsValue(),accessToken:r,testMode:"chat",modelName:l.getFieldValue("auto_router_name"),onClose:()=>{o(!1),c(!1)},onTestComplete:()=>c(!1)},m)})]})};let ls=(0,i.n)("guardrails"),la=()=>{let{accessToken:e,userId:l,userRole:t}=(0,n.Z)();return(0,r.a)({queryKey:ls.list({}),queryFn:async()=>(await (0,a.getGuardrailsList)(e)).guardrails.map(e=>e.guardrail_name),enabled:!!(e&&l&&t)})},lr=(0,i.n)("tags"),li=()=>{let{accessToken:e,userId:l,userRole:t}=(0,n.Z)();return(0,r.a)({queryKey:lr.list({}),queryFn:async()=>await (0,a.tagListCall)(e),enabled:!!(e&&l&&t)})};var ln=t(59341),lo=t(51653),ld=t(84376),lc=t(63709),lm=t(26210),lu=t(34766),lh=t(45246),lx=t(24199);let{Text:lp}=Q.default;var lg=e=>{let{form:l,showCacheControl:t,onCacheControlChange:a}=e,r=e=>{let t=l.getFieldValue("litellm_extra_params");try{let s=t?JSON.parse(t):{};e.length>0?s.cache_control_injection_points=e:delete s.cache_control_injection_points,Object.keys(s).length>0?l.setFieldValue("litellm_extra_params",JSON.stringify(s,null,2)):l.setFieldValue("litellm_extra_params","")}catch(e){console.error("Error updating cache control points:",e)}};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(eg.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,s.jsx)(lc.Z,{onChange:a,className:"bg-gray-600"})}),t&&(0,s.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,s.jsx)(lp,{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,s.jsx)(eg.Z.List,{name:"cache_control_injection_points",initialValue:[{location:"message"}],children:(e,t)=>{let{add:a,remove:i}=t;return(0,s.jsxs)(s.Fragment,{children:[e.map((t,a)=>(0,s.jsxs)("div",{className:"flex items-center mb-4 gap-4",children:[(0,s.jsx)(eg.Z.Item,{...t,label:"Type",name:[t.name,"location"],initialValue:"message",className:"mb-0",style:{width:"180px"},children:(0,s.jsx)(ev.default,{disabled:!0,options:[{value:"message",label:"Message"}]})}),(0,s.jsx)(eg.Z.Item,{...t,label:"Role",name:[t.name,"role"],className:"mb-0",style:{width:"180px"},tooltip:"LiteLLM will mark all messages of this role as cacheable",children:(0,s.jsx)(ev.default,{placeholder:"Select a role",allowClear:!0,options:[{value:"user",label:"User"},{value:"system",label:"System"},{value:"assistant",label:"Assistant"}],onChange:()=>{r(l.getFieldValue("cache_control_points"))}})}),(0,s.jsx)(eg.Z.Item,{...t,label:"Index",name:[t.name,"index"],className:"mb-0",style:{width:"180px"},tooltip:"(Optional) If set litellm will mark the message at this index as cacheable",children:(0,s.jsx)(lx.Z,{type:"number",placeholder:"Optional",step:1,onChange:()=>{r(l.getFieldValue("cache_control_points"))}})}),e.length>1&&(0,s.jsx)(lh.Z,{className:"text-red-500 cursor-pointer text-lg ml-12",onClick:()=>{i(t.name),setTimeout(()=>{r(l.getFieldValue("cache_control_points"))},0)}})]},t.key)),(0,s.jsx)(eg.Z.Item,{children:(0,s.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:()=>a(),children:[(0,s.jsx)(e4.Z,{className:"mr-2"}),"Add Injection Point"]})})]})}})]})]})},lf=t(9309);let{Link:lj}=Q.default;var lv=e=>{let{showAdvancedSettings:l,setShowAdvancedSettings:t,teams:a,guardrailsList:r,tagsList:i}=e,[n]=eg.Z.useForm(),[o,d]=f.useState(!1),[c,m]=f.useState("per_token"),[u,h]=f.useState(!1),x=(e,l)=>l&&(isNaN(Number(l))||0>Number(l))?Promise.reject("Please enter a valid positive number"):Promise.resolve();return(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)(lm.UQ,{className:"mt-2 mb-4",children:[(0,s.jsx)(lm._m,{children:(0,s.jsx)("b",{children:"Advanced Settings"})}),(0,s.jsx)(lm.X1,{children:(0,s.jsxs)("div",{className:"bg-white rounded-lg",children:[(0,s.jsx)(eg.Z.Item,{label:"Custom Pricing",name:"custom_pricing",valuePropName:"checked",className:"mb-4",children:(0,s.jsx)(lc.Z,{onChange:e=>{d(e),e||n.setFieldsValue({input_cost_per_token:void 0,output_cost_per_token:void 0,input_cost_per_second:void 0})},className:"bg-gray-600"})}),(0,s.jsx)(eg.Z.Item,{label:(0,s.jsxs)("span",{children:["Guardrails"," ",(0,s.jsx)(M.Z,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(R.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:"Select existing guardrails. Go to 'Guardrails' tab to create new guardrails.",children:(0,s.jsx)(ev.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:r.map(e=>({value:e,label:e}))})}),(0,s.jsx)(eg.Z.Item,{label:"Tags",name:"tags",className:"mb-4",children:(0,s.jsx)(ev.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter tags",options:Object.values(i).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}),o&&(0,s.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,s.jsx)(eg.Z.Item,{label:"Pricing Model",name:"pricing_model",className:"mb-4",children:(0,s.jsx)(ev.default,{defaultValue:"per_token",onChange:e=>m(e),options:[{value:"per_token",label:"Per Million Tokens"},{value:"per_second",label:"Per Second"}]})}),"per_token"===c?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(eg.Z.Item,{label:"Input Cost (per 1M tokens)",name:"input_cost_per_token",rules:[{validator:x}],className:"mb-4",children:(0,s.jsx)(lm.oi,{})}),(0,s.jsx)(eg.Z.Item,{label:"Output Cost (per 1M tokens)",name:"output_cost_per_token",rules:[{validator:x}],className:"mb-4",children:(0,s.jsx)(lm.oi,{})})]}):(0,s.jsx)(eg.Z.Item,{label:"Cost Per Second",name:"input_cost_per_second",rules:[{validator:x}],className:"mb-4",children:(0,s.jsx)(lm.oi,{})})]}),(0,s.jsx)(eg.Z.Item,{label:"Use in pass through routes",name:"use_in_pass_through",valuePropName:"checked",className:"mb-4 mt-4",tooltip:(0,s.jsxs)("span",{children:["Allow using these credentials in pass through routes."," ",(0,s.jsx)(lj,{href:"https://docs.litellm.ai/docs/pass_through/vertex_ai",target:"_blank",children:"Learn more"})]}),children:(0,s.jsx)(lc.Z,{onChange:e=>{let l=n.getFieldValue("litellm_extra_params");try{let t=l?JSON.parse(l):{};e?t.use_in_pass_through=!0:delete t.use_in_pass_through,Object.keys(t).length>0?n.setFieldValue("litellm_extra_params",JSON.stringify(t,null,2)):n.setFieldValue("litellm_extra_params","")}catch(l){e?n.setFieldValue("litellm_extra_params",JSON.stringify({use_in_pass_through:!0},null,2)):n.setFieldValue("litellm_extra_params","")}},className:"bg-gray-600"})}),(0,s.jsx)(lg,{form:n,showCacheControl:u,onCacheControlChange:e=>{if(h(e),!e){let e=n.getFieldValue("litellm_extra_params");try{let l=e?JSON.parse(e):{};delete l.cache_control_injection_points,Object.keys(l).length>0?n.setFieldValue("litellm_extra_params",JSON.stringify(l,null,2)):n.setFieldValue("litellm_extra_params","")}catch(e){n.setFieldValue("litellm_extra_params","")}}}}),(0,s.jsx)(eg.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:lf.Ac}],children:(0,s.jsx)(lu.Z,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}),(0,s.jsxs)(ew.Z,{className:"mb-4",children:[(0,s.jsx)(eZ.Z,{span:10}),(0,s.jsx)(eZ.Z,{span:10,children:(0,s.jsxs)(lm.xv,{className:"text-gray-600 text-sm",children:["Pass JSON of litellm supported params"," ",(0,s.jsx)(lj,{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",children:"litellm.completion() call"})]})})]}),(0,s.jsx)(eg.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:lf.Ac}],children:(0,s.jsx)(lu.Z,{rows:4,placeholder:'{ "mode": "chat" }'})})]})})]})})},l_=t(56609),lb=t(67187);let ly=e=>{let{content:l,children:t,width:a="auto",className:r=""}=e,[i,n]=(0,f.useState)(!1),[o,d]=(0,f.useState)("top"),c=(0,f.useRef)(null),m=()=>{if(c.current){let e=c.current.getBoundingClientRect(),l=e.top,t=window.innerHeight-e.bottom;l<300&&t>300?d("bottom"):d("top")}};return(0,s.jsxs)("div",{className:"relative inline-block",ref:c,children:[t||(0,s.jsx)(lb.Z,{className:"ml-1 text-gray-500 cursor-help",onMouseEnter:()=>{m(),n(!0)},onMouseLeave:()=>n(!1)}),i&&(0,s.jsxs)("div",{className:"absolute left-1/2 -translate-x-1/2 z-50 bg-black/90 text-white p-2 rounded-md text-sm font-normal shadow-lg ".concat(r),style:{["top"===o?"bottom":"top"]:"100%",width:a,marginBottom:"top"===o?"8px":"0",marginTop:"bottom"===o?"8px":"0"},children:[l,(0,s.jsx)("div",{className:"absolute left-1/2 -translate-x-1/2 w-0 h-0",style:{top:"top"===o?"100%":"auto",bottom:"bottom"===o?"100%":"auto",borderTop:"top"===o?"6px solid rgba(0, 0, 0, 0.9)":"6px solid transparent",borderBottom:"bottom"===o?"6px solid rgba(0, 0, 0, 0.9)":"6px solid transparent",borderLeft:"6px solid transparent",borderRight:"6px solid transparent"}})]})]})};var lN=()=>{let e=eg.Z.useFormInstance(),[l,t]=(0,f.useState)(0),a=eg.Z.useWatch("model",e)||[],r=Array.isArray(a)?a:[a],i=eg.Z.useWatch("custom_model_name",e),n=!r.includes("all-wildcard"),o=eg.Z.useWatch("custom_llm_provider",e);if((0,f.useEffect)(()=>{if(i&&r.includes("custom")){let l=(e.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?o===L.Cl.Azure?{public_name:i,litellm_model:"azure/".concat(i)}:{public_name:i,litellm_model:i}:e);e.setFieldValue("model_mappings",l),t(e=>e+1)}},[i,r,o,e]),(0,f.useEffect)(()=>{if(r.length>0&&!r.includes("all-wildcard")){let l=e.getFieldValue("model_mappings")||[];if(l.length!==r.length||!r.every(e=>l.some(l=>"custom"===e?"custom"===l.litellm_model||l.litellm_model===i:o===L.Cl.Azure?l.litellm_model==="azure/".concat(e):l.litellm_model===e))){let l=r.map(e=>"custom"===e&&i?o===L.Cl.Azure?{public_name:i,litellm_model:"azure/".concat(i)}:{public_name:i,litellm_model:i}:o===L.Cl.Azure?{public_name:e,litellm_model:"azure/".concat(e)}:{public_name:e,litellm_model:e});e.setFieldValue("model_mappings",l),t(e=>e+1)}}},[r,i,o,e]),!n)return null;let d=(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{className:"mb-2 font-normal",children:"The name you specify in your API calls to LiteLLM Proxy"}),(0,s.jsxs)("div",{className:"mb-2 font-normal",children:[(0,s.jsx)("strong",{children:"Example:"})," If you name your public model"," ",(0,s.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"example-name"}),", and choose"," ",(0,s.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"openai/qwen-plus-latest"})," as the LiteLLM model"]}),(0,s.jsxs)("div",{className:"mb-2 font-normal",children:[(0,s.jsx)("strong",{children:"Usage:"})," You make an API call to the LiteLLM proxy with"," ",(0,s.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:'model = "example-name"'})]}),(0,s.jsxs)("div",{className:"font-normal",children:[(0,s.jsx)("strong",{children:"Result:"})," LiteLLM sends"," ",(0,s.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"qwen-plus-latest"})," to the provider"]})]}),c=(0,s.jsx)("div",{children:"The model name LiteLLM will send to the LLM API"}),m=[{title:(0,s.jsxs)("span",{className:"flex items-center",children:["Public Model Name",(0,s.jsx)(ly,{content:d,width:"500px"})]}),dataIndex:"public_name",key:"public_name",render:(l,t,a)=>(0,s.jsx)(ej.o,{value:l,onChange:l=>{let t=l.target.value,s=[...e.getFieldValue("model_mappings")],r=o===L.Cl.Anthropic,i=t.endsWith("-1m"),n=e.getFieldValue("litellm_extra_params"),d=!n||""===n.trim(),c=t;if(r&&i&&d){let l=JSON.stringify({extra_headers:{"anthropic-beta":"context-1m-2025-08-07"}},null,2);e.setFieldValue("litellm_extra_params",l),c=t.slice(0,-3)}s[a].public_name=c,e.setFieldValue("model_mappings",s)}})},{title:(0,s.jsxs)("span",{className:"flex items-center",children:["LiteLLM Model Name",(0,s.jsx)(ly,{content:c,width:"360px"})]}),dataIndex:"litellm_model",key:"litellm_model"}];return(0,s.jsx)(s.Fragment,{children:(0,s.jsx)(eg.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",rules:[{required:!0,validator:async(e,l)=>{if(!l||0===l.length)throw Error("At least one model mapping is required");if(l.filter(e=>!e.public_name||""===e.public_name.trim()).length>0)throw Error("All model mappings must have valid public names")}}],children:(0,s.jsx)(l_.Z,{dataSource:e.getFieldValue("model_mappings"),columns:m,pagination:!1,size:"small"},l)})})},lw=e=>{let{selectedProvider:l,providerModels:t,getPlaceholder:a}=e,r=eg.Z.useFormInstance(),i=e=>{let t=e.target.value,s=(r.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?l===L.Cl.Azure?{public_name:t,litellm_model:"azure/".concat(t)}:{public_name:t,litellm_model:t}:e);r.setFieldsValue({model_mappings:s})};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)(eg.Z.Item,{label:"LiteLLM Model Name(s)",tooltip:"The model name LiteLLM will send to the LLM API",className:"mb-0",children:[(0,s.jsx)(eg.Z.Item,{name:"model",rules:[{required:!0,message:"Please enter ".concat(l===L.Cl.Azure?"a deployment name":"at least one model",".")}],noStyle:!0,children:l===L.Cl.Azure||l===L.Cl.OpenAI_Compatible||l===L.Cl.Ollama?(0,s.jsx)(s.Fragment,{children:(0,s.jsx)(eN.o,{placeholder:a(l),onChange:l===L.Cl.Azure?e=>{let l=e.target.value,t=l?[{public_name:l,litellm_model:"azure/".concat(l)}]:[];r.setFieldsValue({model:l,model_mappings:t})}:void 0})}):t.length>0?(0,s.jsx)(ev.default,{mode:"multiple",allowClear:!0,showSearch:!0,placeholder:"Select models",onChange:e=>{let t=Array.isArray(e)?e:[e];if(t.includes("all-wildcard"))r.setFieldsValue({model_name:void 0,model_mappings:[]});else if(JSON.stringify(r.getFieldValue("model"))!==JSON.stringify(t)){let e=t.map(e=>l===L.Cl.Azure?{public_name:e,litellm_model:"azure/".concat(e)}:{public_name:e,litellm_model:e});r.setFieldsValue({model:t,model_mappings:e})}},optionFilterProp:"children",filterOption:(e,l)=>{var t;return(null!==(t=null==l?void 0:l.label)&&void 0!==t?t:"").toLowerCase().includes(e.toLowerCase())},options:[{label:"Custom Model Name (Enter below)",value:"custom"},{label:"All ".concat(l," Models (Wildcard)"),value:"all-wildcard"},...t.map(e=>({label:e,value:e}))],style:{width:"100%"}}):(0,s.jsx)(eN.o,{placeholder:a(l)})}),(0,s.jsx)(eg.Z.Item,{noStyle:!0,shouldUpdate:(e,l)=>e.model!==l.model,children:e=>{let{getFieldValue:t}=e,a=t("model")||[];return(Array.isArray(a)?a:[a]).includes("custom")&&(0,s.jsx)(eg.Z.Item,{name:"custom_model_name",rules:[{required:!0,message:"Please enter a custom model name."}],className:"mt-2",children:(0,s.jsx)(eN.o,{placeholder:l===L.Cl.Azure?"Enter Azure deployment name":"Enter custom model name",onChange:i})})}})]}),(0,s.jsxs)(ew.Z,{children:[(0,s.jsx)(eZ.Z,{span:10}),(0,s.jsx)(eZ.Z,{span:14,children:(0,s.jsx)(eN.x,{className:"mb-3 mt-1",children:l===L.Cl.Azure?"Your deployment name will be saved as the public model name, and LiteLLM will use 'azure/deployment-name' internally":"The model name LiteLLM will send to the LLM API"})})]})]})};let lZ=[{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:"video_generation",label:"Video Generation - /videos"},{value:"rerank",label:"Rerank - /rerank"},{value:"realtime",label:"Realtime - /realtime"},{value:"batch",label:"Batch - /batch"},{value:"ocr",label:"OCR - /ocr"}],{Title:lC,Link:lk}=Q.default;var lS=e=>{let{form:l,handleOk:t,selectedProvider:r,setSelectedProvider:i,providerModels:o,setProviderModelsFn:d,getPlaceholder:c,uploadProps:m,showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x,credentials:p}=e,[g,j]=(0,f.useState)("chat"),[v,b]=(0,f.useState)(!1),[y,N]=(0,f.useState)(!1),[w,Z]=(0,f.useState)(""),{accessToken:C,userRole:k,premiumUser:S,userId:A}=(0,n.Z)(),{data:E,isLoading:P,error:I}=eb(),{data:T,isLoading:R,error:O}=la(),{data:V,isLoading:q,error:z}=li(),B=async()=>{N(!0),Z("test-".concat(Date.now())),b(!0)},[G,U]=(0,f.useState)(!1),[H,K]=(0,f.useState)([]),[J,W]=(0,f.useState)(null);(0,f.useEffect)(()=>{(async()=>{K((await (0,a.modelAvailableCall)(C,"","",!1,null,!0,!0)).data.map(e=>e.id))})()},[C]);let Y=(0,f.useMemo)(()=>E?[...E].sort((e,l)=>e.provider_display_name.localeCompare(l.provider_display_name)):[],[E]),$=I?I instanceof Error?I.message:"Failed to load providers":null,X=eR.ZL.includes(k),ee=(0,eR.yV)(x,A);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(lC,{level:2,children:"Add Model"}),(0,s.jsx)(et.Z,{children:(0,s.jsx)(eg.Z,{form:l,onFinish:async e=>{console.log("\uD83D\uDD25 Form onFinish triggered with values:",e),await t().then(()=>{W(null)})},onFinishFailed:e=>{console.log("\uD83D\uDCA5 Form onFinishFailed triggered:",e)},labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:(0,s.jsxs)(s.Fragment,{children:[ee&&!X&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(eg.Z.Item,{label:"Select Team",name:"team_id",rules:[{required:!0,message:"Please select a team to continue"}],tooltip:"Select the team for which you want to add this model",children:(0,s.jsx)(ld.Z,{teams:x,onChange:e=>{W(e)}})}),!J&&(0,s.jsx)(lo.Z,{message:"Team Selection Required",description:"As a team admin, you need to select your team first before adding models.",type:"info",showIcon:!0,className:"mb-4"})]}),(X||ee&&J)&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(eg.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,s.jsxs)(ev.default,{virtual:!1,showSearch:!0,loading:P,placeholder:P?"Loading providers...":"Select a provider",optionFilterProp:"data-label",onChange:e=>{i(e),d(e),l.setFieldsValue({custom_llm_provider:e}),l.setFieldsValue({model:[],model_name:void 0})},children:[$&&0===Y.length&&(0,s.jsx)(ev.default.Option,{value:"",children:$},"__error"),Y.map(e=>{let l=e.provider_display_name,t=e.provider;return L.cd[l],(0,s.jsx)(ev.default.Option,{value:t,"data-label":l,children:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)(F,{provider:t,className:"w-5 h-5"}),(0,s.jsx)("span",{children:l})]})},t)})]})}),(0,s.jsx)(lw,{selectedProvider:r,providerModels:o,getPlaceholder:c}),(0,s.jsx)(lN,{}),(0,s.jsx)(eg.Z.Item,{label:"Mode",name:"mode",className:"mb-1",children:(0,s.jsx)(ev.default,{style:{width:"100%"},value:g,onChange:e=>j(e),options:lZ})}),(0,s.jsxs)(ew.Z,{children:[(0,s.jsx)(eZ.Z,{span:10}),(0,s.jsx)(eZ.Z,{span:10,children:(0,s.jsxs)(D.Z,{className:"mb-5 mt-1",children:[(0,s.jsx)("strong",{children:"Optional"})," - LiteLLM endpoint to use when health checking this model"," ",(0,s.jsx)(lk,{href:"https://docs.litellm.ai/docs/proxy/health#health",target:"_blank",children:"Learn more"})]})})]}),(0,s.jsx)("div",{className:"mb-4",children:(0,s.jsx)(Q.default.Text,{className:"text-sm text-gray-500 mb-2",children:"Either select existing credentials OR enter new provider credentials below"})}),(0,s.jsx)(eg.Z.Item,{label:"Existing Credentials",name:"litellm_credential_name",initialValue:null,children:(0,s.jsx)(ev.default,{showSearch:!0,placeholder:"Select or search for existing credentials",optionFilterProp:"children",filterOption:(e,l)=>{var t;return(null!==(t=null==l?void 0:l.label)&&void 0!==t?t:"").toLowerCase().includes(e.toLowerCase())},options:[{value:null,label:"None"},...p.map(e=>({value:e.credential_name,label:e.credential_name}))],allowClear:!0})}),(0,s.jsx)(eg.Z.Item,{noStyle:!0,shouldUpdate:(e,l)=>e.litellm_credential_name!==l.litellm_credential_name||e.provider!==l.provider,children:e=>{let{getFieldValue:l}=e,t=l("litellm_credential_name");return(console.log("\uD83D\uDD11 Credential Name Changed:",t),t)?null:(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{className:"flex items-center my-4",children:[(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,s.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"OR"}),(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,s.jsx)(eP,{selectedProvider:r,uploadProps:m})]})}}),(0,s.jsxs)("div",{className:"flex items-center my-4",children:[(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,s.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Additional Model Info Settings"}),(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(X||!ee)&&(0,s.jsx)(eg.Z.Item,{label:"Team-BYOK Model",tooltip:"Only use this model + credential combination for this team. Useful when teams want to onboard their own OpenAI keys.",className:"mb-4",children:(0,s.jsx)(M.Z,{title:S?"":"This is an enterprise-only feature. Upgrade to premium to restrict model+credential combinations to a specific team.",placement:"top",children:(0,s.jsx)(ln.Z,{checked:G,onChange:e=>{U(e),e||l.setFieldValue("team_id",void 0)},disabled:!S})})}),G&&(X||!ee)&&(0,s.jsx)(eg.Z.Item,{label:"Select Team",name:"team_id",className:"mb-4",tooltip:"Only keys for this team will be able to call this model.",rules:[{required:G&&!X,message:"Please select a team."}],children:(0,s.jsx)(ld.Z,{teams:x,disabled:!S})}),X&&(0,s.jsx)(s.Fragment,{children:(0,s.jsx)(eg.Z.Item,{label:"Model Access Group",name:"model_access_group",className:"mb-4",tooltip:"Use model access groups to give users access to select models, and add new ones to the group over time.",children:(0,s.jsx)(ev.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],options:H.map(e=>({value:e,label:e})),maxTagCount:"responsive",allowClear:!0})})}),(0,s.jsx)(lv,{showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x,guardrailsList:T||[],tagsList:V||{}})]}),(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,s.jsx)(M.Z,{title:"Get help on our github",children:(0,s.jsx)(Q.default.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{className:"space-x-2",children:[(0,s.jsx)(_.ZP,{onClick:B,loading:y,children:"Test Connect"}),(0,s.jsx)(_.ZP,{htmlType:"submit",children:"Add Model"})]})]})]})})}),(0,s.jsx)(ea.Z,{title:"Connection Test Results",open:v,onCancel:()=>{b(!1),N(!1)},footer:[(0,s.jsx)(_.ZP,{onClick:()=>{b(!1),N(!1)},children:"Close"},"close")],width:700,children:v&&(0,s.jsx)(eQ,{formValues:l.getFieldsValue(),accessToken:C,testMode:g,modelName:l.getFieldValue("model_name")||l.getFieldValue("model"),onClose:()=>{b(!1),N(!1)},onTestComplete:()=>N(!1)},w)})]})},lA=e=>{let{form:l,handleOk:t,selectedProvider:a,setSelectedProvider:r,providerModels:i,setProviderModelsFn:n,getPlaceholder:o,uploadProps:d,showAdvancedSettings:c,setShowAdvancedSettings:m,teams:u,credentials:h,accessToken:x,userRole:p}=e,[g]=eg.Z.useForm();return(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)(eH.v0,{className:"w-full",children:[(0,s.jsxs)(eH.td,{className:"mb-4",children:[(0,s.jsx)(eH.OK,{children:"Add Model"}),(0,s.jsx)(eH.OK,{children:"Add Auto Router"})]}),(0,s.jsxs)(eH.nP,{children:[(0,s.jsx)(eH.x4,{children:(0,s.jsx)(lS,{form:l,handleOk:t,selectedProvider:a,setSelectedProvider:r,providerModels:i,setProviderModelsFn:n,getPlaceholder:o,uploadProps:d,showAdvancedSettings:c,setShowAdvancedSettings:m,teams:u,credentials:h})}),(0,s.jsx)(eH.x4,{children:(0,s.jsx)(lt,{form:g,handleOk:()=>{g.validateFields().then(e=>{e0(e,x,g,t)}).catch(e=>{console.error("Validation failed:",e)})},accessToken:x,userRole:p})})]})]})})},lE=t(8048),lP=t(4156),lM=t(15731),lL=t(91126);let lF=(e,l,t,a,r,i,n,o,d,c,m)=>[{header:()=>(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(lP.Z,{checked:t,indeterminate:l.length>0&&!t,onChange:e=>r(e.target.checked),onClick:e=>e.stopPropagation()}),(0,s.jsx)("span",{children:"Model ID"})]}),accessorKey:"model_info.id",enableSorting:!0,sortingFn:"alphanumeric",cell:e=>{let{row:t}=e,r=t.original,i=r.model_name,n=l.includes(i);return(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(lP.Z,{checked:n,onChange:e=>a(i,e.target.checked),onClick:e=>e.stopPropagation()}),(0,s.jsx)(M.Z,{title:r.model_info.id,children:(0,s.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 max-w-[15ch]",onClick:()=>m&&m(r.model_info.id),children:r.model_info.id})})]})}},{header:"Model Name",accessorKey:"model_name",enableSorting:!0,sortingFn:"alphanumeric",cell:e=>{let{row:l}=e,t=l.original,a=o(t)||t.model_name;return(0,s.jsx)("div",{className:"font-medium text-sm",children:(0,s.jsx)(M.Z,{title:a,children:(0,s.jsx)("div",{className:"truncate max-w-[200px]",children:a})})})}},{header:"Health Status",accessorKey:"health_status",enableSorting:!0,sortingFn:(e,l,t)=>{var s,a;let r=e.getValue("health_status")||"unknown",i=l.getValue("health_status")||"unknown",n={healthy:0,checking:1,unknown:2,unhealthy:3};return(null!==(s=n[r])&&void 0!==s?s:4)-(null!==(a=n[i])&&void 0!==a?a:4)},cell:l=>{var t;let{row:a}=l,r=a.original,i={status:r.health_status,loading:r.health_loading,error:r.health_error};if(i.loading)return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsxs)("div",{className:"flex space-x-1",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse"}),(0,s.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse",style:{animationDelay:"0.2s"}}),(0,s.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse",style:{animationDelay:"0.4s"}})]}),(0,s.jsx)(e3.x,{className:"text-gray-600 text-sm",children:"Checking..."})]});let o=r.model_name,d="healthy"===i.status&&(null===(t=e[o])||void 0===t?void 0:t.successResponse);return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[n(i.status),d&&c&&(0,s.jsx)(M.Z,{title:"View response details",placement:"top",children:(0,s.jsx)("button",{onClick:()=>{var l;return c(o,null===(l=e[o])||void 0===l?void 0:l.successResponse)},className:"p-1 text-green-600 hover:text-green-800 hover:bg-green-50 rounded cursor-pointer transition-colors",children:(0,s.jsx)(lM.Z,{className:"h-4 w-4"})})})]})}},{header:"Error Details",accessorKey:"health_error",enableSorting:!1,cell:l=>{let{row:t}=l,a=t.original.model_name,r=e[a];if(!(null==r?void 0:r.error))return(0,s.jsx)(e3.x,{className:"text-gray-400 text-sm",children:"No errors"});let i=r.error,n=r.fullError||r.error;return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("div",{className:"max-w-[200px]",children:(0,s.jsx)(M.Z,{title:i,placement:"top",children:(0,s.jsx)(e3.x,{className:"text-red-600 text-sm truncate",children:i})})}),d&&n!==i&&(0,s.jsx)(M.Z,{title:"View full error details",placement:"top",children:(0,s.jsx)("button",{onClick:()=>d(a,i,n),className:"p-1 text-red-600 hover:text-red-800 hover:bg-red-50 rounded cursor-pointer transition-colors",children:(0,s.jsx)(lM.Z,{className:"h-4 w-4"})})})]})}},{header:"Last Check",accessorKey:"last_check",enableSorting:!0,sortingFn:(e,l,t)=>{let s=e.getValue("last_check")||"Never checked",a=l.getValue("last_check")||"Never checked";if("Never checked"===s&&"Never checked"===a)return 0;if("Never checked"===s)return 1;if("Never checked"===a)return -1;if("Check in progress..."===s&&"Check in progress..."===a)return 0;if("Check in progress..."===s)return -1;if("Check in progress..."===a)return 1;let r=new Date(s),i=new Date(a);return isNaN(r.getTime())&&isNaN(i.getTime())?0:isNaN(r.getTime())?1:isNaN(i.getTime())?-1:i.getTime()-r.getTime()},cell:e=>{let{row:l}=e,t=l.original;return(0,s.jsx)(e3.x,{className:"text-gray-600 text-sm",children:t.health_loading?"Check in progress...":t.last_check})}},{header:"Last Success",accessorKey:"last_success",enableSorting:!0,sortingFn:(e,l,t)=>{let s=e.getValue("last_success")||"Never succeeded",a=l.getValue("last_success")||"Never succeeded";if("Never succeeded"===s&&"Never succeeded"===a)return 0;if("Never succeeded"===s)return 1;if("Never succeeded"===a)return -1;if("None"===s&&"None"===a)return 0;if("None"===s)return 1;if("None"===a)return -1;let r=new Date(s),i=new Date(a);return isNaN(r.getTime())&&isNaN(i.getTime())?0:isNaN(r.getTime())?1:isNaN(i.getTime())?-1:i.getTime()-r.getTime()},cell:l=>{let{row:t}=l,a=e[t.original.model_name],r=(null==a?void 0:a.lastSuccess)||"None";return(0,s.jsx)(e3.x,{className:"text-gray-600 text-sm",children:r})}},{header:"Actions",id:"actions",cell:e=>{let{row:l}=e,t=l.original,a=t.model_name,r=t.health_status&&"none"!==t.health_status,n=t.health_loading?"Checking...":r?"Re-run Health Check":"Run Health Check";return(0,s.jsx)(M.Z,{title:n,placement:"top",children:(0,s.jsx)("button",{className:"p-2 rounded-md transition-colors ".concat(t.health_loading?"text-gray-400 cursor-not-allowed bg-gray-100":"text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50"),onClick:()=>{t.health_loading||i(a)},disabled:t.health_loading,children:t.health_loading?(0,s.jsxs)("div",{className:"flex space-x-1",children:[(0,s.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse"}),(0,s.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse",style:{animationDelay:"0.2s"}}),(0,s.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse",style:{animationDelay:"0.4s"}})]}):r?(0,s.jsx)(eO.Z,{className:"h-4 w-4"}):(0,s.jsx)(lL.Z,{className:"h-4 w-4"})})})},enableSorting:!1}],lI=[{pattern:/Missing .* API Key/i,replacement:"Missing API Key"},{pattern:/Connection timeout/i,replacement:"Connection timeout"},{pattern:/Network.*not.*ok/i,replacement:"Network connection failed"},{pattern:/403.*Forbidden/i,replacement:"Access forbidden - check API key permissions"},{pattern:/401.*Unauthorized/i,replacement:"Unauthorized - invalid API key"},{pattern:/429.*rate limit/i,replacement:"Rate limit exceeded"},{pattern:/500.*Internal Server Error/i,replacement:"Provider internal server error"},{pattern:/litellm\.AuthenticationError/i,replacement:"Authentication failed"},{pattern:/litellm\.RateLimitError/i,replacement:"Rate limit exceeded"},{pattern:/litellm\.APIError/i,replacement:"API error"}];var lT=e=>{let{accessToken:l,modelData:t,all_models_on_proxy:r,getDisplayModelName:i,setSelectedModelId:n}=e,[o,d]=(0,f.useState)({}),[c,m]=(0,f.useState)([]),[u,h]=(0,f.useState)(!1),[x,p]=(0,f.useState)(!1),[g,j]=(0,f.useState)(null),[v,b]=(0,f.useState)(!1),[y,N]=(0,f.useState)(null);(0,f.useRef)(null),(0,f.useEffect)(()=>{l&&(null==t?void 0:t.data)&&(async()=>{let e={};t.data.forEach(l=>{e[l.model_name]={status:"none",lastCheck:"None",lastSuccess:"None",loading:!1,error:void 0,fullError:void 0,successResponse:void 0}});try{let s=await (0,a.latestHealthChecksCall)(l);s&&s.latest_health_checks&&"object"==typeof s.latest_health_checks&&Object.entries(s.latest_health_checks).forEach(l=>{let[s,a]=l;if(!a)return;let r=null,i=t.data.find(e=>e.model_name===s);if(i)r=i.model_name;else{let e=t.data.find(e=>e.model_info&&e.model_info.id===s);if(e)r=e.model_name;else if(a.model_name){let e=t.data.find(e=>e.model_name===a.model_name);e&&(r=e.model_name)}}if(r){let l=a.error_message||void 0;e[r]={status:a.status||"unknown",lastCheck:a.checked_at?new Date(a.checked_at).toLocaleString():"None",lastSuccess:"healthy"===a.status&&a.checked_at?new Date(a.checked_at).toLocaleString():"None",loading:!1,error:l?w(l):void 0,fullError:l,successResponse:"healthy"===a.status?a:void 0}}})}catch(e){console.warn("Failed to load health check history (using default states):",e)}d(e)})()},[l,t]);let w=e=>{var l;if(!e)return"Health check failed";let t="string"==typeof e?e:JSON.stringify(e),s=t.match(/(\w+Error):\s*(\d{3})/i);if(s)return"".concat(s[1],": ").concat(s[2]);let a=t.match(/(AuthenticationError|RateLimitError|BadRequestError|InternalServerError|TimeoutError|NotFoundError|ForbiddenError|ServiceUnavailableError|BadGatewayError|ContentPolicyViolationError|\w+Error)/i),r=t.match(/\b(400|401|403|404|408|429|500|502|503|504)\b/);if(a&&r)return"".concat(a[1],": ").concat(r[1]);if(r){let e=r[1];return"".concat({400:"BadRequestError",401:"AuthenticationError",403:"ForbiddenError",404:"NotFoundError",408:"TimeoutError",429:"RateLimitError",500:"InternalServerError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError"}[e],": ").concat(e)}if(a){let e=a[1],l={AuthenticationError:"401",RateLimitError:"429",BadRequestError:"400",InternalServerError:"500",TimeoutError:"408",NotFoundError:"404",ForbiddenError:"403",ServiceUnavailableError:"503",BadGatewayError:"502",GatewayTimeoutError:"504",ContentPolicyViolationError:"400"}[e];return l?"".concat(e,": ").concat(l):e}for(let{pattern:e,replacement:l}of lI)if(e.test(t))return l;if(/missing.*api.*key|invalid.*key|unauthorized/i.test(t))return"AuthenticationError: 401";if(/rate.*limit|too.*many.*requests/i.test(t))return"RateLimitError: 429";if(/timeout|timed.*out/i.test(t))return"TimeoutError: 408";if(/not.*found/i.test(t))return"NotFoundError: 404";if(/forbidden|access.*denied/i.test(t))return"ForbiddenError: 403";if(/internal.*server.*error/i.test(t))return"InternalServerError: 500";let i=t.replace(/[\n\r]+/g," ").replace(/\s+/g," ").trim(),n=null===(l=i.split(/[.!?]/)[0])||void 0===l?void 0:l.trim();return n&&n.length>0?n.length>100?n.substring(0,97)+"...":n:i.length>100?i.substring(0,97)+"...":i},Z=async e=>{if(l){d(l=>({...l,[e]:{...l[e],loading:!0,status:"checking"}}));try{var s,r;let i=await (0,a.individualModelHealthCheckCall)(l,e),n=new Date().toLocaleString();if(i.unhealthy_count>0&&i.unhealthy_endpoints&&i.unhealthy_endpoints.length>0){let l=(null===(s=i.unhealthy_endpoints[0])||void 0===s?void 0:s.error)||"Health check failed",t=w(l);d(s=>{var a;return{...s,[e]:{status:"unhealthy",lastCheck:n,lastSuccess:(null===(a=s[e])||void 0===a?void 0:a.lastSuccess)||"None",loading:!1,error:t,fullError:l}}})}else d(l=>({...l,[e]:{status:"healthy",lastCheck:n,lastSuccess:n,loading:!1,successResponse:i}}));try{let s=await (0,a.latestHealthChecksCall)(l),i=t.data.find(l=>l.model_name===e);if(i){let l=i.model_info.id,t=null===(r=s.latest_health_checks)||void 0===r?void 0:r[l];if(t){let l=t.error_message||void 0;d(s=>{var a,r,i,n,o,d,c;return{...s,[e]:{status:t.status||(null===(a=s[e])||void 0===a?void 0:a.status)||"unknown",lastCheck:t.checked_at?new Date(t.checked_at).toLocaleString():(null===(r=s[e])||void 0===r?void 0:r.lastCheck)||"None",lastSuccess:"healthy"===t.status?t.checked_at?new Date(t.checked_at).toLocaleString():(null===(i=s[e])||void 0===i?void 0:i.lastSuccess)||"None":(null===(n=s[e])||void 0===n?void 0:n.lastSuccess)||"None",loading:!1,error:l?w(l):null===(o=s[e])||void 0===o?void 0:o.error,fullError:l||(null===(d=s[e])||void 0===d?void 0:d.fullError),successResponse:"healthy"===t.status?t:null===(c=s[e])||void 0===c?void 0:c.successResponse}}})}}}catch(e){console.debug("Could not fetch updated status from database (non-critical):",e)}}catch(a){let l=new Date().toLocaleString(),t=a instanceof Error?a.message:String(a),s=w(t);d(a=>{var r;return{...a,[e]:{status:"unhealthy",lastCheck:l,lastSuccess:(null===(r=a[e])||void 0===r?void 0:r.lastSuccess)||"None",loading:!1,error:s,fullError:t}}})}}},C=async()=>{let e=c.length>0?c:r,s=e.reduce((e,l)=>(e[l]={...o[l],loading:!0,status:"checking"},e),{});d(e=>({...e,...s}));let i={},n=e.map(async e=>{if(l)try{let s=await (0,a.individualModelHealthCheckCall)(l,e);i[e]=s;let r=new Date().toLocaleString();if(s.unhealthy_count>0&&s.unhealthy_endpoints&&s.unhealthy_endpoints.length>0){var t;let l=(null===(t=s.unhealthy_endpoints[0])||void 0===t?void 0:t.error)||"Health check failed",a=w(l);d(t=>{var s;return{...t,[e]:{status:"unhealthy",lastCheck:r,lastSuccess:(null===(s=t[e])||void 0===s?void 0:s.lastSuccess)||"None",loading:!1,error:a,fullError:l}}})}else d(l=>({...l,[e]:{status:"healthy",lastCheck:r,lastSuccess:r,loading:!1,successResponse:s}}))}catch(a){console.error("Health check failed for ".concat(e,":"),a);let l=new Date().toLocaleString(),t=a instanceof Error?a.message:String(a),s=w(t);d(a=>{var r;return{...a,[e]:{status:"unhealthy",lastCheck:l,lastSuccess:(null===(r=a[e])||void 0===r?void 0:r.lastSuccess)||"None",loading:!1,error:s,fullError:t}}})}});await Promise.allSettled(n);try{if(!l)return;let s=await (0,a.latestHealthChecksCall)(l);s.latest_health_checks&&Object.entries(s.latest_health_checks).forEach(l=>{let[s,a]=l,r=t.data.find(e=>e.model_info.id===s);if(r&&e.includes(r.model_name)&&a){let e=r.model_name,l=a.error_message||void 0;d(t=>{let s=t[e];return{...t,[e]:{status:a.status||(null==s?void 0:s.status)||"unknown",lastCheck:a.checked_at?new Date(a.checked_at).toLocaleString():(null==s?void 0:s.lastCheck)||"None",lastSuccess:"healthy"===a.status&&a.checked_at?new Date(a.checked_at).toLocaleString():(null==s?void 0:s.lastSuccess)||"None",loading:!1,error:l?w(l):null==s?void 0:s.error,fullError:l||(null==s?void 0:s.fullError),successResponse:"healthy"===a.status?a:null==s?void 0:s.successResponse}}})}})}catch(e){console.warn("Failed to fetch updated health statuses from database (non-critical):",e)}},k=e=>{h(e),e?m(r):m([])},S=()=>{p(!1),j(null)},P=()=>{b(!1),N(null)};return(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"mb-6",children:(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(W.Z,{children:"Model Health Status"}),(0,s.jsx)(D.Z,{className:"text-gray-600 mt-1",children:"Run health checks on individual models to verify they are working correctly"})]}),(0,s.jsxs)("div",{className:"flex items-center gap-3",children:[c.length>0&&(0,s.jsx)(E.Z,{size:"sm",variant:"light",onClick:()=>k(!1),className:"px-3 py-1 text-sm",children:"Clear Selection"}),(0,s.jsx)(E.Z,{size:"sm",variant:"secondary",onClick:C,disabled:Object.values(o).some(e=>e.loading),className:"px-3 py-1 text-sm",children:c.length>0&&c.length{l?m(l=>[...l,e]):(m(l=>l.filter(l=>l!==e)),h(!1))},k,Z,e=>{switch(e){case"healthy":return(0,s.jsx)(A.Z,{color:"emerald",children:"healthy"});case"unhealthy":return(0,s.jsx)(A.Z,{color:"red",children:"unhealthy"});case"checking":return(0,s.jsx)(A.Z,{color:"blue",children:"checking"});case"none":return(0,s.jsx)(A.Z,{color:"gray",children:"none"});default:return(0,s.jsx)(A.Z,{color:"gray",children:"unknown"})}},i,(e,l,t)=>{j({modelName:e,cleanedError:l,fullError:t}),p(!0)},(e,l)=>{N({modelName:e,response:l}),b(!0)},n),data:t.data.map(e=>{let l=o[e.model_name]||{status:"none",lastCheck:"None",loading:!1};return{model_name:e.model_name,model_info:e.model_info,provider:e.provider,litellm_model_name:e.litellm_model_name,health_status:l.status,last_check:l.lastCheck,last_success:l.lastSuccess||"None",health_loading:l.loading,health_error:l.error,health_full_error:l.fullError}}),isLoading:!1})}),(0,s.jsx)(ea.Z,{title:g?"Health Check Error - ".concat(g.modelName):"Error Details",open:x,onCancel:S,footer:[(0,s.jsx)(_.ZP,{onClick:S,children:"Close"},"close")],width:800,children:g&&(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Error:"}),(0,s.jsx)("div",{className:"mt-2 p-3 bg-red-50 border border-red-200 rounded-md",children:(0,s.jsx)(D.Z,{className:"text-red-800",children:g.cleanedError})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Full Error Details:"}),(0,s.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md max-h-96 overflow-y-auto",children:(0,s.jsx)("pre",{className:"text-sm text-gray-800 whitespace-pre-wrap",children:g.fullError})})]})]})}),(0,s.jsx)(ea.Z,{title:y?"Health Check Response - ".concat(y.modelName):"Response Details",open:v,onCancel:P,footer:[(0,s.jsx)(_.ZP,{onClick:P,children:"Close"},"close")],width:800,children:y&&(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Status:"}),(0,s.jsx)("div",{className:"mt-2 p-3 bg-green-50 border border-green-200 rounded-md",children:(0,s.jsx)(D.Z,{className:"text-green-800",children:"Health check passed successfully"})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Response Details:"}),(0,s.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md max-h-96 overflow-y-auto",children:(0,s.jsx)("pre",{className:"text-sm text-gray-800 whitespace-pre-wrap",children:JSON.stringify(y.response,null,2)})})]})]})})]})},lR=t(47686),lO=t(77355),lV=t(93416),lq=t(95704),lz=e=>{let{accessToken:l,initialModelGroupAlias:t={},onAliasUpdate:r}=e,[i,n]=(0,f.useState)([]),[o,d]=(0,f.useState)({aliasName:"",targetModelGroup:""}),[c,m]=(0,f.useState)(null),[u,h]=(0,f.useState)(!0);(0,f.useEffect)(()=>{n(Object.entries(t).map((e,l)=>{var t;let[s,a]=e;return{id:"".concat(l,"-").concat(s),aliasName:s,targetModelGroup:"string"==typeof a?a:null!==(t=null==a?void 0:a.model)&&void 0!==t?t:""}}))},[t]);let x=async e=>{if(!l)return console.error("Access token is missing"),!1;try{let t={};return e.forEach(e=>{t[e.aliasName]=e.targetModelGroup}),console.log("Saving model group alias:",t),await (0,a.setCallbacksCall)(l,{router_settings:{model_group_alias:t}}),r&&r(t),!0}catch(e){return console.error("Failed to save model group alias settings:",e),eo.Z.fromBackend("Failed to save model group alias settings"),!1}},p=async()=>{if(!o.aliasName||!o.targetModelGroup){eo.Z.fromBackend("Please provide both alias name and target model group");return}if(i.some(e=>e.aliasName===o.aliasName)){eo.Z.fromBackend("An alias with this name already exists");return}let e=[...i,{id:"".concat(Date.now(),"-").concat(o.aliasName),aliasName:o.aliasName,targetModelGroup:o.targetModelGroup}];await x(e)&&(n(e),d({aliasName:"",targetModelGroup:""}),eo.Z.success("Alias added successfully"))},g=e=>{m({...e})},j=async()=>{if(!c)return;if(!c.aliasName||!c.targetModelGroup){eo.Z.fromBackend("Please provide both alias name and target model group");return}if(i.some(e=>e.id!==c.id&&e.aliasName===c.aliasName)){eo.Z.fromBackend("An alias with this name already exists");return}let e=i.map(e=>e.id===c.id?c:e);await x(e)&&(n(e),m(null),eo.Z.success("Alias updated successfully"))},v=()=>{m(null)},_=async e=>{let l=i.filter(l=>l.id!==e);await x(l)&&(n(l),eo.Z.success("Alias deleted successfully"))},b=i.reduce((e,l)=>(e[l.aliasName]=l.targetModelGroup,e),{});return(0,s.jsxs)(lq.Zb,{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between cursor-pointer",onClick:()=>h(!u),children:[(0,s.jsxs)("div",{className:"flex flex-col",children:[(0,s.jsx)(lq.Dx,{className:"mb-0",children:"Model Group Alias Settings"}),(0,s.jsx)("p",{className:"text-sm text-gray-500",children:"Create aliases for your model groups to simplify API calls. For example, you can create an alias 'gpt-4o' that points to 'gpt-4o-mini-openai' model group."})]}),(0,s.jsx)("div",{className:"flex items-center",children:u?(0,s.jsx)(y.Z,{className:"w-5 h-5 text-gray-500"}):(0,s.jsx)(lR.Z,{className:"w-5 h-5 text-gray-500"})})]}),u&&(0,s.jsxs)("div",{className:"mt-4",children:[(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsx)(lq.xv,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,s.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,s.jsx)("input",{type:"text",value:o.aliasName,onChange:e=>d({...o,aliasName:e.target.value}),placeholder:"e.g., gpt-4o",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model Group"}),(0,s.jsx)("input",{type:"text",value:o.targetModelGroup,onChange:e=>d({...o,targetModelGroup:e.target.value}),placeholder:"e.g., gpt-4o-mini-openai",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]}),(0,s.jsx)("div",{className:"flex items-end",children:(0,s.jsxs)("button",{onClick:p,disabled:!o.aliasName||!o.targetModelGroup,className:"flex items-center px-4 py-2 rounded-md text-sm ".concat(o.aliasName&&o.targetModelGroup?"bg-green-600 text-white hover:bg-green-700":"bg-gray-300 text-gray-500 cursor-not-allowed"),children:[(0,s.jsx)(lO.Z,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,s.jsx)(lq.xv,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,s.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,s.jsx)("div",{className:"overflow-x-auto",children:(0,s.jsxs)(lq.iA,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,s.jsx)(lq.ss,{children:(0,s.jsxs)(lq.SC,{children:[(0,s.jsx)(lq.xs,{className:"py-1 h-8",children:"Alias Name"}),(0,s.jsx)(lq.xs,{className:"py-1 h-8",children:"Target Model Group"}),(0,s.jsx)(lq.xs,{className:"py-1 h-8",children:"Actions"})]})}),(0,s.jsxs)(lq.RM,{children:[i.map(e=>(0,s.jsx)(lq.SC,{className:"h-8",children:c&&c.id===e.id?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(lq.pj,{className:"py-0.5",children:(0,s.jsx)("input",{type:"text",value:c.aliasName,onChange:e=>m({...c,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,s.jsx)(lq.pj,{className:"py-0.5",children:(0,s.jsx)("input",{type:"text",value:c.targetModelGroup,onChange:e=>m({...c,targetModelGroup:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,s.jsx)(lq.pj,{className:"py-0.5 whitespace-nowrap",children:(0,s.jsxs)("div",{className:"flex space-x-2",children:[(0,s.jsx)("button",{onClick:j,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,s.jsx)("button",{onClick:v,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(lq.pj,{className:"py-0.5 text-sm text-gray-900",children:e.aliasName}),(0,s.jsx)(lq.pj,{className:"py-0.5 text-sm text-gray-500",children:e.targetModelGroup}),(0,s.jsx)(lq.pj,{className:"py-0.5 whitespace-nowrap",children:(0,s.jsxs)("div",{className:"flex space-x-2",children:[(0,s.jsx)("button",{onClick:()=>g(e),className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,s.jsx)(lV.Z,{className:"w-3 h-3"})}),(0,s.jsx)("button",{onClick:()=>_(e.id),className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,s.jsx)(S.Z,{className:"w-3 h-3"})})]})})]})},e.id)),0===i.length&&(0,s.jsx)(lq.SC,{children:(0,s.jsx)(lq.pj,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),(0,s.jsxs)(lq.Zb,{children:[(0,s.jsx)(lq.Dx,{className:"mb-4",children:"Configuration Example"}),(0,s.jsx)(lq.xv,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config.yaml:"}),(0,s.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,s.jsxs)("div",{className:"text-gray-700",children:["router_settings:",(0,s.jsx)("br",{}),"\xa0\xa0model_group_alias:",0===Object.keys(b).length?(0,s.jsxs)("span",{className:"text-gray-500",children:[(0,s.jsx)("br",{}),"\xa0\xa0\xa0\xa0# No aliases configured yet"]}):Object.entries(b).map(e=>{let[l,t]=e;return(0,s.jsxs)("span",{children:[(0,s.jsx)("br",{}),'\xa0\xa0\xa0\xa0"',l,'": "',t,'"']},l)})]})})]})]})]})},lD=t(10900),lB=t(12514),lG=t(49566),lU=t(30401),lH=t(78867),lK=t(59872),lJ=e=>{let{isVisible:l,onCancel:t,onSuccess:r,modelData:i,accessToken:n,userRole:o}=e,[d]=eg.Z.useForm(),[c,m]=(0,f.useState)(!1),[u,h]=(0,f.useState)([]),[x,p]=(0,f.useState)([]),[g,j]=(0,f.useState)(!1),[v,b]=(0,f.useState)(!1),[y,N]=(0,f.useState)(null);(0,f.useEffect)(()=>{l&&i&&w()},[l,i]),(0,f.useEffect)(()=>{let e=async()=>{if(n)try{let e=await (0,a.modelAvailableCall)(n,"","",!1,null,!0,!0);h(e.data.map(e=>e.id))}catch(e){console.error("Error fetching model access groups:",e)}},t=async()=>{if(n)try{let e=await (0,e1.p)(n);p(e)}catch(e){console.error("Error fetching model info:",e)}};l&&(e(),t())},[l,n]);let w=()=>{try{var e,l,t,s,a,r;let n=null;(null===(e=i.litellm_params)||void 0===e?void 0:e.auto_router_config)&&(n="string"==typeof i.litellm_params.auto_router_config?JSON.parse(i.litellm_params.auto_router_config):i.litellm_params.auto_router_config),N(n),d.setFieldsValue({auto_router_name:i.model_name,auto_router_default_model:(null===(l=i.litellm_params)||void 0===l?void 0:l.auto_router_default_model)||"",auto_router_embedding_model:(null===(t=i.litellm_params)||void 0===t?void 0:t.auto_router_embedding_model)||"",model_access_group:(null===(s=i.model_info)||void 0===s?void 0:s.access_groups)||[]});let o=new Set(x.map(e=>e.model_group));j(!o.has(null===(a=i.litellm_params)||void 0===a?void 0:a.auto_router_default_model)),b(!o.has(null===(r=i.litellm_params)||void 0===r?void 0:r.auto_router_embedding_model))}catch(e){console.error("Error parsing auto router config:",e),eo.Z.fromBackend("Error loading auto router configuration")}},Z=async()=>{try{m(!0);let e=await d.validateFields(),l={...i.litellm_params,auto_router_config:JSON.stringify(y),auto_router_default_model:e.auto_router_default_model,auto_router_embedding_model:e.auto_router_embedding_model||void 0},s={...i.model_info,access_groups:e.model_access_group||[]},o={model_name:e.auto_router_name,litellm_params:l,model_info:s};await (0,a.modelPatchUpdateCall)(n,o,i.model_info.id);let c={...i,model_name:e.auto_router_name,litellm_params:l,model_info:s};eo.Z.success("Auto router configuration updated successfully"),r(c),t()}catch(e){console.error("Error updating auto router:",e),eo.Z.fromBackend("Failed to update auto router configuration")}finally{m(!1)}},C=x.map(e=>({value:e.model_group,label:e.model_group}));return(0,s.jsx)(ea.Z,{title:"Edit Auto Router Configuration",open:l,onCancel:t,footer:[(0,s.jsx)(_.ZP,{onClick:t,children:"Cancel"},"cancel"),(0,s.jsx)(_.ZP,{loading:c,onClick:Z,children:"Save Changes"},"submit")],width:1e3,destroyOnClose:!0,children:(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsx)(eN.x,{className:"text-gray-600",children:"Edit the auto router configuration including routing logic, default models, and access settings."}),(0,s.jsxs)(eg.Z,{form:d,layout:"vertical",className:"space-y-4",children:[(0,s.jsx)(eg.Z.Item,{label:"Auto Router Name",name:"auto_router_name",rules:[{required:!0,message:"Auto router name is required"}],children:(0,s.jsx)(eN.o,{placeholder:"e.g., auto_router_1, smart_routing"})}),(0,s.jsx)("div",{className:"w-full",children:(0,s.jsx)(e9,{modelInfo:x,value:y,onChange:e=>{N(e)}})}),(0,s.jsx)(eg.Z.Item,{label:"Default Model",name:"auto_router_default_model",rules:[{required:!0,message:"Default model is required"}],children:(0,s.jsx)(ev.default,{placeholder:"Select a default model",onChange:e=>{j("custom"===e)},options:[...C,{value:"custom",label:"Enter custom model name"}],showSearch:!0})}),(0,s.jsx)(eg.Z.Item,{label:"Embedding Model",name:"auto_router_embedding_model",children:(0,s.jsx)(ev.default,{placeholder:"Select an embedding model (optional)",onChange:e=>{b("custom"===e)},options:[...C,{value:"custom",label:"Enter custom model name"}],showSearch:!0,allowClear:!0})}),"Admin"===o&&(0,s.jsx)(eg.Z.Item,{label:"Model Access Groups",name:"model_access_group",tooltip:"Control who can access this auto router",children:(0,s.jsx)(ev.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],options:u.map(e=>({value:e,label:e})),maxTagCount:"responsive",allowClear:!0})})]})]})})};let{Title:lW,Link:lY}=Q.default;var l$=e=>{let{isVisible:l,onCancel:t,onAddCredential:a,existingCredential:r,setIsCredentialModalOpen:i}=e,[n]=eg.Z.useForm();return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(r))),(0,s.jsx)(ea.Z,{title:"Reuse Credentials",visible:l,onCancel:()=>{t(),n.resetFields()},footer:null,width:600,children:(0,s.jsxs)(eg.Z,{form:n,onFinish:e=>{a(e),n.resetFields(),i(!1)},layout:"vertical",children:[(0,s.jsx)(eg.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==r?void 0:r.credential_name,children:(0,s.jsx)(ej.o,{placeholder:"Enter a friendly name for these credentials"})}),Object.entries((null==r?void 0:r.credential_values)||{}).map(e=>{let[l,t]=e;return(0,s.jsx)(eg.Z.Item,{label:l,name:l,initialValue:t,children:(0,s.jsx)(ej.o,{placeholder:"Enter ".concat(l),disabled:!0})},l)}),(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(M.Z,{title:"Get help on our github",children:(0,s.jsx)(lY,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(_.ZP,{onClick:()=>{t(),n.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,s.jsx)(_.ZP,{htmlType:"submit",children:"Reuse Credentials"})]})]})]})})};function lX(e){var l,t,r,i,n,o,d,c,h,x,p,g,j,v,b,y,N,w,Z,C,A,P,F,I,V,q,B,G,U,H,J,Y,$;let{modelId:X,onClose:Q,accessToken:ee,userID:el,userRole:et,onModelUpdate:es,modelAccessGroups:er}=e,[ei]=eg.Z.useForm(),[en,ed]=(0,f.useState)(null),[ec,em]=(0,f.useState)(!1),[eu,eh]=(0,f.useState)(!1),[ex,ep]=(0,f.useState)(!1),[ej,e_]=(0,f.useState)(!1),[eb,ey]=(0,f.useState)(!1),[eN,ew]=(0,f.useState)(!1),[eZ,eC]=(0,f.useState)(null),[eS,eA]=(0,f.useState)(!1),[eE,eP]=(0,f.useState)({}),[eM,eL]=(0,f.useState)(!1),[eF,eI]=(0,f.useState)([]),[eT,eR]=(0,f.useState)({}),{data:eV,isLoading:eq}=(0,u.XP)(1,50,void 0,X),{data:eU}=m(),{data:eH}=(0,u.VI)(),eK=e=>null!=eU&&"object"==typeof eU&&e in eU?eU[e].litellm_provider:"openai",eJ=(0,f.useMemo)(()=>(null==eV?void 0:eV.data)&&0!==eV.data.length&&K(eV,eK).data[0]||null,[eV,eU]),eW=("Admin"===et||(null==eJ?void 0:null===(l=eJ.model_info)||void 0===l?void 0:l.created_by)===el)&&(null==eJ?void 0:null===(t=eJ.model_info)||void 0===t?void 0:t.db_model),eY="Admin"===et,e$=(null==eJ?void 0:null===(r=eJ.litellm_params)||void 0===r?void 0:r.auto_router_config)!=null,eX=(null==eJ?void 0:null===(i=eJ.litellm_params)||void 0===i?void 0:i.litellm_credential_name)!=null&&(null==eJ?void 0:null===(n=eJ.litellm_params)||void 0===n?void 0:n.litellm_credential_name)!=void 0;(0,f.useEffect)(()=>{if(eJ&&!en){var e,l,t,s,a,r,i;let n=eJ;n.litellm_model_name||(n={...n,litellm_model_name:null!==(i=null!==(r=null!==(a=null==n?void 0:null===(l=n.litellm_params)||void 0===l?void 0:l.litellm_model_name)&&void 0!==a?a:null==n?void 0:null===(t=n.litellm_params)||void 0===t?void 0:t.model)&&void 0!==r?r:null==n?void 0:null===(s=n.model_info)||void 0===s?void 0:s.key)&&void 0!==i?i:null}),ed(n),(null==n?void 0:null===(e=n.litellm_params)||void 0===e?void 0:e.cache_control_injection_points)&&eA(!0)}},[eJ,en]),(0,f.useEffect)(()=>{let e=async()=>{var e,l,t,s,r,i,n;if(!ee||eJ)return;let o=await (0,a.modelInfoV1Call)(ee,X);console.log("modelInfoResponse, ",o);let d=o.data[0];d&&!d.litellm_model_name&&(d={...d,litellm_model_name:null!==(n=null!==(i=null!==(r=null==d?void 0:null===(l=d.litellm_params)||void 0===l?void 0:l.litellm_model_name)&&void 0!==r?r:null==d?void 0:null===(t=d.litellm_params)||void 0===t?void 0:t.model)&&void 0!==i?i:null==d?void 0:null===(s=d.model_info)||void 0===s?void 0:s.key)&&void 0!==n?n:null}),ed(d),(null==d?void 0:null===(e=d.litellm_params)||void 0===e?void 0:e.cache_control_injection_points)&&eA(!0)},l=async()=>{if(ee)try{let e=(await (0,a.getGuardrailsList)(ee)).guardrails.map(e=>e.guardrail_name);eI(e)}catch(e){console.error("Failed to fetch guardrails:",e)}},t=async()=>{if(ee)try{let e=await (0,a.tagListCall)(ee);eR(e)}catch(e){console.error("Failed to fetch tags:",e)}};(async()=>{if(console.log("accessToken, ",ee),!ee||eX)return;let e=await (0,a.credentialGetCall)(ee,null,X);console.log("existingCredentialResponse, ",e),eC({credential_name:e.credential_name,credential_values:e.credential_values,credential_info:e.credential_info})})(),e(),l(),t()},[ee,X]);let eQ=async e=>{var l;if(console.log("values, ",e),!ee)return;let t={credential_name:e.credential_name,model_id:X,credential_info:{custom_llm_provider:null===(l=en.litellm_params)||void 0===l?void 0:l.custom_llm_provider}};eo.Z.info("Storing credential.."),console.log("credentialResponse, ",await (0,a.credentialCreateCall)(ee,t)),eo.Z.success("Credential stored successfully")},e0=async e=>{try{var l;let t;if(!ee)return;ey(!0),console.log("values.model_name, ",e.model_name);let s={};try{s=e.litellm_extra_params?JSON.parse(e.litellm_extra_params):{}}catch(e){eo.Z.fromBackend("Invalid JSON in LiteLLM Params"),ey(!1);return}let r={...e.litellm_params,...s,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,tags:e.tags};e.guardrails&&(r.guardrails=e.guardrails),e.cache_control&&(null===(l=e.cache_control_injection_points)||void 0===l?void 0:l.length)>0?r.cache_control_injection_points=e.cache_control_injection_points:delete r.cache_control_injection_points;try{t=e.model_info?JSON.parse(e.model_info):eJ.model_info,e.model_access_group&&(t={...t,access_groups:e.model_access_group}),void 0!==e.health_check_model&&(t={...t,health_check_model:e.health_check_model})}catch(e){eo.Z.fromBackend("Invalid JSON in Model Info");return}let i={model_name:e.model_name,litellm_params:r,model_info:t};await (0,a.modelPatchUpdateCall)(ee,i,X);let n={...en,model_name:e.model_name,litellm_model_name:e.litellm_model_name,litellm_params:r,model_info:t};ed(n),es&&es(n),eo.Z.success("Model settings updated successfully"),e_(!1),ew(!1)}catch(e){console.error("Error updating model:",e),eo.Z.fromBackend("Failed to update model settings")}finally{ey(!1)}};if(eq)return(0,s.jsxs)("div",{className:"p-4",children:[(0,s.jsx)(E.Z,{icon:lD.Z,variant:"light",onClick:Q,className:"mb-4",children:"Back to Models"}),(0,s.jsx)(D.Z,{children:"Loading..."})]});if(!eJ)return(0,s.jsxs)("div",{className:"p-4",children:[(0,s.jsx)(E.Z,{icon:lD.Z,variant:"light",onClick:Q,className:"mb-4",children:"Back to Models"}),(0,s.jsx)(D.Z,{children:"Model not found"})]});let e1=async()=>{if(ee)try{var e,l,t;eo.Z.info("Testing connection...");let s=await (0,a.testConnectionRequest)(ee,{custom_llm_provider:en.litellm_params.custom_llm_provider,litellm_credential_name:en.litellm_params.litellm_credential_name,model:en.litellm_model_name},{mode:null===(e=en.model_info)||void 0===e?void 0:e.mode},null===(l=en.model_info)||void 0===l?void 0:l.mode);if("success"===s.status)eo.Z.success("Connection test successful!");else throw Error((null==s?void 0:null===(t=s.result)||void 0===t?void 0:t.error)||(null==s?void 0:s.message)||"Unknown error")}catch(e){e instanceof Error?eo.Z.error("Error testing connection: "+(0,lf.aS)(e.message,100)):eo.Z.error("Error testing connection: "+String(e))}},e2=async()=>{try{if(eh(!0),!ee)return;await (0,a.modelDeleteCall)(ee,X),eo.Z.success("Model deleted successfully"),es&&es({deleted:!0,model_info:{id:X}}),Q()}catch(e){console.error("Error deleting the model:",e),eo.Z.fromBackend("Failed to delete model")}finally{eh(!1),em(!1)}},e4=async(e,l)=>{await (0,lK.vQ)(e)&&(eP(e=>({...e,[l]:!0})),setTimeout(()=>{eP(e=>({...e,[l]:!1}))},2e3))},e5=eJ.litellm_model_name.includes("*");return console.log("isWildcardModel, ",e5),(0,s.jsxs)("div",{className:"p-4",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(E.Z,{icon:lD.Z,variant:"light",onClick:Q,className:"mb-4",children:"Back to Models"}),(0,s.jsxs)(W.Z,{children:["Public Model Name: ",T(eJ)]}),(0,s.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,s.jsx)(D.Z,{className:"text-gray-500 font-mono",children:eJ.model_info.id}),(0,s.jsx)(_.ZP,{type:"text",size:"small",icon:eE["model-id"]?(0,s.jsx)(lU.Z,{size:12}):(0,s.jsx)(lH.Z,{size:12}),onClick:()=>e4(eJ.model_info.id,"model-id"),className:"left-2 z-10 transition-all duration-200 ".concat(eE["model-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100")})]})]}),(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)(E.Z,{variant:"secondary",icon:eO.Z,onClick:e1,className:"flex items-center gap-2","data-testid":"test-connection-button",children:"Test Connection"}),(0,s.jsx)(E.Z,{icon:k.Z,variant:"secondary",onClick:()=>ep(!0),className:"flex items-center",disabled:!eY,"data-testid":"reuse-credentials-button",children:"Re-use Credentials"}),(0,s.jsx)(E.Z,{icon:S.Z,variant:"secondary",onClick:()=>em(!0),className:"flex items-center text-red-500 border-red-500 hover:text-red-700",disabled:!eW,"data-testid":"delete-model-button",children:"Delete Model"})]})]}),(0,s.jsxs)(eD.Z,{children:[(0,s.jsxs)(eB.Z,{className:"mb-6",children:[(0,s.jsx)(ez.Z,{children:"Overview"}),(0,s.jsx)(ez.Z,{children:"Raw JSON"})]}),(0,s.jsxs)(eG.Z,{children:[(0,s.jsxs)(z.Z,{children:[(0,s.jsxs)(O.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6 mb-6",children:[(0,s.jsxs)(lB.Z,{children:[(0,s.jsx)(D.Z,{children:"Provider"}),(0,s.jsxs)("div",{className:"mt-2 flex items-center space-x-2",children:[eJ.provider&&(0,s.jsx)("img",{src:(0,L.dr)(eJ.provider).logo,alt:"".concat(eJ.provider," logo"),className:"w-4 h-4",onError:e=>{let l=e.currentTarget,t=l.parentElement;if(t&&t.contains(l))try{var s;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===(s=eJ.provider)||void 0===s?void 0:s.charAt(0))||"-",t.replaceChild(e,l)}catch(e){console.error("Failed to replace provider logo fallback:",e)}}}),(0,s.jsx)(W.Z,{children:eJ.provider||"Not Set"})]})]}),(0,s.jsxs)(lB.Z,{children:[(0,s.jsx)(D.Z,{children:"LiteLLM Model"}),(0,s.jsx)("div",{className:"mt-2 overflow-hidden",children:(0,s.jsx)(M.Z,{title:eJ.litellm_model_name||"Not Set",children:(0,s.jsx)("div",{className:"break-all text-sm font-medium leading-relaxed cursor-pointer",children:eJ.litellm_model_name||"Not Set"})})})]}),(0,s.jsxs)(lB.Z,{children:[(0,s.jsx)(D.Z,{children:"Pricing"}),(0,s.jsxs)("div",{className:"mt-2",children:[(0,s.jsxs)(D.Z,{children:["Input: $",eJ.input_cost,"/1M tokens"]}),(0,s.jsxs)(D.Z,{children:["Output: $",eJ.output_cost,"/1M tokens"]})]})]})]}),(0,s.jsxs)("div",{className:"mb-6 text-sm text-gray-500 flex items-center gap-x-6",children:[(0,s.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,s.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,s.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"," ",eJ.model_info.created_at?new Date(eJ.model_info.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Not Set"]}),(0,s.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,s.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,s.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 ",eJ.model_info.created_by||"Not Set"]})]}),(0,s.jsxs)(lB.Z,{children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,s.jsx)(W.Z,{children:"Model Settings"}),(0,s.jsxs)("div",{className:"flex gap-2",children:[e$&&eW&&!eN&&(0,s.jsx)(E.Z,{onClick:()=>eL(!0),className:"flex items-center",children:"Edit Auto Router"}),eW?!eN&&(0,s.jsx)(E.Z,{onClick:()=>ew(!0),className:"flex items-center",children:"Edit Settings"}):(0,s.jsx)(M.Z,{title:"Only DB models can be edited. You must be an admin or the creator of the model to edit it.",children:(0,s.jsx)(R.Z,{})})]})]}),en?(0,s.jsx)(eg.Z,{form:ei,onFinish:e0,initialValues:{model_name:en.model_name,litellm_model_name:en.litellm_model_name,api_base:en.litellm_params.api_base,custom_llm_provider:en.litellm_params.custom_llm_provider,organization:en.litellm_params.organization,tpm:en.litellm_params.tpm,rpm:en.litellm_params.rpm,max_retries:en.litellm_params.max_retries,timeout:en.litellm_params.timeout,stream_timeout:en.litellm_params.stream_timeout,input_cost:en.litellm_params.input_cost_per_token?1e6*en.litellm_params.input_cost_per_token:(null===(o=en.model_info)||void 0===o?void 0:o.input_cost_per_token)*1e6||null,output_cost:(null===(d=en.litellm_params)||void 0===d?void 0:d.output_cost_per_token)?1e6*en.litellm_params.output_cost_per_token:(null===(c=en.model_info)||void 0===c?void 0:c.output_cost_per_token)*1e6||null,cache_control:null!==(h=en.litellm_params)&&void 0!==h&&!!h.cache_control_injection_points,cache_control_injection_points:(null===(x=en.litellm_params)||void 0===x?void 0:x.cache_control_injection_points)||[],model_access_group:Array.isArray(null===(p=en.model_info)||void 0===p?void 0:p.access_groups)?en.model_info.access_groups:[],guardrails:Array.isArray(null===(g=en.litellm_params)||void 0===g?void 0:g.guardrails)?en.litellm_params.guardrails:[],tags:Array.isArray(null===(j=en.litellm_params)||void 0===j?void 0:j.tags)?en.litellm_params.tags:[],health_check_model:e5?null===(v=en.model_info)||void 0===v?void 0:v.health_check_model:null,litellm_extra_params:JSON.stringify(en.litellm_params||{},null,2)},layout:"vertical",onValuesChange:()=>e_(!0),children:(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Model Name"}),eN?(0,s.jsx)(eg.Z.Item,{name:"model_name",className:"mb-0",children:(0,s.jsx)(lG.Z,{placeholder:"Enter model name"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:en.model_name})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"LiteLLM Model Name"}),eN?(0,s.jsx)(eg.Z.Item,{name:"litellm_model_name",className:"mb-0",children:(0,s.jsx)(lG.Z,{placeholder:"Enter LiteLLM model name"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:en.litellm_model_name})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Input Cost (per 1M tokens)"}),eN?(0,s.jsx)(eg.Z.Item,{name:"input_cost",className:"mb-0",children:(0,s.jsx)(lx.Z,{placeholder:"Enter input cost"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==en?void 0:null===(b=en.litellm_params)||void 0===b?void 0:b.input_cost_per_token)?((null===(y=en.litellm_params)||void 0===y?void 0:y.input_cost_per_token)*1e6).toFixed(4):(null==en?void 0:null===(N=en.model_info)||void 0===N?void 0:N.input_cost_per_token)?(1e6*en.model_info.input_cost_per_token).toFixed(4):null})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Output Cost (per 1M tokens)"}),eN?(0,s.jsx)(eg.Z.Item,{name:"output_cost",className:"mb-0",children:(0,s.jsx)(lx.Z,{placeholder:"Enter output cost"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==en?void 0:null===(w=en.litellm_params)||void 0===w?void 0:w.output_cost_per_token)?(1e6*en.litellm_params.output_cost_per_token).toFixed(4):(null==en?void 0:null===(Z=en.model_info)||void 0===Z?void 0:Z.output_cost_per_token)?(1e6*en.model_info.output_cost_per_token).toFixed(4):null})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"API Base"}),eN?(0,s.jsx)(eg.Z.Item,{name:"api_base",className:"mb-0",children:(0,s.jsx)(lG.Z,{placeholder:"Enter API base"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(C=en.litellm_params)||void 0===C?void 0:C.api_base)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Custom LLM Provider"}),eN?(0,s.jsx)(eg.Z.Item,{name:"custom_llm_provider",className:"mb-0",children:(0,s.jsx)(lG.Z,{placeholder:"Enter custom LLM provider"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(A=en.litellm_params)||void 0===A?void 0:A.custom_llm_provider)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Organization"}),eN?(0,s.jsx)(eg.Z.Item,{name:"organization",className:"mb-0",children:(0,s.jsx)(lG.Z,{placeholder:"Enter organization"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(P=en.litellm_params)||void 0===P?void 0:P.organization)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"TPM (Tokens per Minute)"}),eN?(0,s.jsx)(eg.Z.Item,{name:"tpm",className:"mb-0",children:(0,s.jsx)(lx.Z,{placeholder:"Enter TPM"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(F=en.litellm_params)||void 0===F?void 0:F.tpm)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"RPM (Requests per Minute)"}),eN?(0,s.jsx)(eg.Z.Item,{name:"rpm",className:"mb-0",children:(0,s.jsx)(lx.Z,{placeholder:"Enter RPM"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(I=en.litellm_params)||void 0===I?void 0:I.rpm)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Max Retries"}),eN?(0,s.jsx)(eg.Z.Item,{name:"max_retries",className:"mb-0",children:(0,s.jsx)(lx.Z,{placeholder:"Enter max retries"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(V=en.litellm_params)||void 0===V?void 0:V.max_retries)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Timeout (seconds)"}),eN?(0,s.jsx)(eg.Z.Item,{name:"timeout",className:"mb-0",children:(0,s.jsx)(lx.Z,{placeholder:"Enter timeout"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(q=en.litellm_params)||void 0===q?void 0:q.timeout)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Stream Timeout (seconds)"}),eN?(0,s.jsx)(eg.Z.Item,{name:"stream_timeout",className:"mb-0",children:(0,s.jsx)(lx.Z,{placeholder:"Enter stream timeout"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(B=en.litellm_params)||void 0===B?void 0:B.stream_timeout)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Model Access Groups"}),eN?(0,s.jsx)(eg.Z.Item,{name:"model_access_group",className:"mb-0",children:(0,s.jsx)(ev.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],maxTagCount:"responsive",allowClear:!0,style:{width:"100%"},options:null==er?void 0:er.map(e=>({value:e,label:e}))})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(G=en.model_info)||void 0===G?void 0:G.access_groups)?Array.isArray(en.model_info.access_groups)?en.model_info.access_groups.length>0?(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:en.model_info.access_groups.map((e,l)=>(0,s.jsx)("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800",children:e},l))}):"No groups assigned":en.model_info.access_groups:"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsxs)(D.Z,{className:"font-medium",children:["Guardrails",(0,s.jsx)(M.Z,{title:"Apply safety guardrails to this model to filter content or enforce policies",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(R.Z,{style:{marginLeft:"4px"}})})})]}),eN?(0,s.jsx)(eg.Z.Item,{name:"guardrails",className:"mb-0",children:(0,s.jsx)(ev.default,{mode:"tags",showSearch:!0,placeholder:"Select existing guardrails or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],maxTagCount:"responsive",allowClear:!0,style:{width:"100%"},options:eF.map(e=>({value:e,label:e}))})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(U=en.litellm_params)||void 0===U?void 0:U.guardrails)?Array.isArray(en.litellm_params.guardrails)?en.litellm_params.guardrails.length>0?(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:en.litellm_params.guardrails.map((e,l)=>(0,s.jsx)("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800",children:e},l))}):"No guardrails assigned":en.litellm_params.guardrails:"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Tags"}),eN?(0,s.jsx)(eg.Z.Item,{name:"tags",className:"mb-0",children:(0,s.jsx)(ev.default,{mode:"tags",showSearch:!0,placeholder:"Select existing tags or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],maxTagCount:"responsive",allowClear:!0,style:{width:"100%"},options:Object.values(eT).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(H=en.litellm_params)||void 0===H?void 0:H.tags)?Array.isArray(en.litellm_params.tags)?en.litellm_params.tags.length>0?(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:en.litellm_params.tags.map((e,l)=>(0,s.jsx)("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800",children:e},l))}):"No tags assigned":en.litellm_params.tags:"Not Set"})]}),e5&&(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Health Check Model"}),eN?(0,s.jsx)(eg.Z.Item,{name:"health_check_model",className:"mb-0",children:(0,s.jsx)(ev.default,{showSearch:!0,placeholder:"Select existing health check model",optionFilterProp:"children",allowClear:!0,options:(()=>{var e;let l=eJ.litellm_model_name.split("/")[0];return(null==eH?void 0:null===(e=eH.data)||void 0===e?void 0:e.filter(e=>{var t;return(null===(t=e.providers)||void 0===t?void 0:t.includes(l))&&e.model_group!==eJ.litellm_model_name}).map(e=>({value:e.model_group,label:e.model_group})))||[]})()})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(J=en.model_info)||void 0===J?void 0:J.health_check_model)||"Not Set"})]}),eN?(0,s.jsx)(lg,{form:ei,showCacheControl:eS,onCacheControlChange:e=>eA(e)}):(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Cache Control"}),(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(Y=en.litellm_params)||void 0===Y?void 0:Y.cache_control_injection_points)?(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{children:"Enabled"}),(0,s.jsx)("div",{className:"mt-2",children:en.litellm_params.cache_control_injection_points.map((e,l)=>(0,s.jsxs)("div",{className:"text-sm text-gray-600 mb-1",children:["Location: ",e.location,",",e.role&&(0,s.jsxs)("span",{children:[" Role: ",e.role]}),void 0!==e.index&&(0,s.jsxs)("span",{children:[" Index: ",e.index]})]},l))})]}):"Disabled"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Model Info"}),eN?(0,s.jsx)(eg.Z.Item,{name:"model_info",className:"mb-0",children:(0,s.jsx)(ek.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}',defaultValue:JSON.stringify(eJ.model_info,null,2)})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(0,s.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(en.model_info,null,2)})})]}),(0,s.jsxs)("div",{children:[(0,s.jsxs)(D.Z,{className:"font-medium",children:["LiteLLM Params",(0,s.jsx)(M.Z,{title:"Optional litellm params used for making a litellm.completion() call. Some params are automatically added by LiteLLM.",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(R.Z,{style:{marginLeft:"4px"}})})})]}),eN?(0,s.jsx)(eg.Z.Item,{name:"litellm_extra_params",rules:[{validator:lf.Ac}],children:(0,s.jsx)(ek.default.TextArea,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(0,s.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(en.litellm_params,null,2)})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(D.Z,{className:"font-medium",children:"Team ID"}),(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:eJ.model_info.team_id||"Not Set"})]})]}),eN&&(0,s.jsxs)("div",{className:"mt-6 flex justify-end gap-2",children:[(0,s.jsx)(E.Z,{variant:"secondary",onClick:()=>{ei.resetFields(),e_(!1),ew(!1)},disabled:eb,children:"Cancel"}),(0,s.jsx)(E.Z,{variant:"primary",onClick:()=>ei.submit(),loading:eb,children:"Save Changes"})]})]})}):(0,s.jsx)(D.Z,{children:"Loading..."})]})]}),(0,s.jsx)(z.Z,{children:(0,s.jsx)(lB.Z,{children:(0,s.jsx)("pre",{className:"bg-gray-100 p-4 rounded text-xs overflow-auto",children:JSON.stringify(eJ,null,2)})})})]})]}),(0,s.jsx)(ef.Z,{isOpen:ec,title:"Delete Model",alertMessage:"This action cannot be undone.",message:"Are you sure you want to delete this model?",resourceInformationTitle:"Model Information",resourceInformation:[{label:"Model Name",value:(null==eJ?void 0:eJ.model_name)||"Not Set"},{label:"LiteLLM Model Name",value:(null==eJ?void 0:eJ.litellm_model_name)||"Not Set"},{label:"Provider",value:(null==eJ?void 0:eJ.provider)||"Not Set"},{label:"Created By",value:(null==eJ?void 0:null===($=eJ.model_info)||void 0===$?void 0:$.created_by)||"Not Set"}],onCancel:()=>em(!1),onOk:e2,confirmLoading:eu}),ex&&!eX?(0,s.jsx)(l$,{isVisible:ex,onCancel:()=>ep(!1),onAddCredential:eQ,existingCredential:eZ,setIsCredentialModalOpen:ep}):(0,s.jsx)(ea.Z,{open:ex,onCancel:()=>ep(!1),title:"Using Existing Credential",children:(0,s.jsx)(D.Z,{children:eJ.litellm_params.litellm_credential_name})}),(0,s.jsx)(lJ,{isVisible:eM,onCancel:()=>eL(!1),onSuccess:e=>{ed(e),es&&es(e)},modelData:en||eJ,accessToken:ee||"",userRole:et||""})]})}var lQ=t(27593),l0=t(56147),l1=e=>{var l;let{premiumUser:t,teams:r}=e,{accessToken:i,token:o,userRole:c,userId:x}=(0,n.Z)(),[p]=eg.Z.useForm(),[g,j]=(0,f.useState)(""),[v,_]=(0,f.useState)([]),[b,y]=(0,f.useState)(L.Cl.Anthropic),[N,w]=(0,f.useState)(null),[Z,C]=(0,f.useState)(null),[k,S]=(0,f.useState)(null),[A,E]=(0,f.useState)(0),[M,F]=(0,f.useState)({}),[I,R]=(0,f.useState)(!1),[V,q]=(0,f.useState)(null),[B,G]=(0,f.useState)(null),[U,H]=(0,f.useState)(0),W=(0,eV.NL)(),{data:Y,isLoading:$,refetch:ee}=(0,u.XP)(),{data:el,isLoading:et}=m(),{data:es,isLoading:ea}=d(),er=(null==es?void 0:es.credentials)||[],{data:ei,isLoading:en}=(0,h.L)(),ed=(0,f.useMemo)(()=>{if(!(null==Y?void 0:Y.data))return[];let e=new Set;for(let l of Y.data)e.add(l.model_name);return Array.from(e).sort()},[null==Y?void 0:Y.data]),ec=(0,f.useMemo)(()=>{if(!(null==Y?void 0:Y.data))return[];let e=new Set;for(let l of Y.data){let t=l.model_info;if(null==t?void 0:t.access_groups)for(let l of t.access_groups)e.add(l)}return Array.from(e)},[null==Y?void 0:Y.data]),eu=(0,f.useMemo)(()=>(null==Y?void 0:Y.data)?Y.data.map(e=>e.model_name):[],[null==Y?void 0:Y.data]),ex=e=>null!=el&&"object"==typeof el&&e in el?el[e].litellm_provider:"openai",ep=(0,f.useMemo)(()=>(null==Y?void 0:Y.data)?K(Y,ex):{data:[]},[null==Y?void 0:Y.data,ex]),ef=c&&(0,eR.P4)(c),ej=c&&eR.lo.includes(c),ev=x&&(0,eR.yV)(r,x),e_=ej&&(null==ei?void 0:null===(l=ei.values)||void 0===l?void 0:l.disable_model_add_for_internal_users)===!0,eb=!ef&&(e_||!ev),ey={name:"file",accept:".json",pastable:!1,beforeUpload:e=>{if("application/json"===e.type){let l=new FileReader;l.onload=e=>{if(e.target){let l=e.target.result;p.setFieldsValue({vertex_credentials:l})}},l.readAsText(e)}return!1},onChange(e){"done"===e.file.status?eo.Z.success("".concat(e.file.name," file uploaded successfully")):"error"===e.file.status&&eo.Z.fromBackend("".concat(e.file.name," file upload failed."))}},eN=()=>{j(new Date().toLocaleString()),W.invalidateQueries({queryKey:["models","list"]}),ee()},ew=async()=>{if(i)try{let e={router_settings:{}};"global"===N?(k&&(e.router_settings.retry_policy=k),eo.Z.success("Global retry settings saved successfully")):(Z&&(e.router_settings.model_group_retry_policy=Z),eo.Z.success("Retry settings saved successfully for ".concat(N))),await (0,a.setCallbacksCall)(i,e)}catch(e){eo.Z.fromBackend("Failed to save retry settings")}};if((0,f.useEffect)(()=>{if(!i||!o||!c||!x||!Y)return;let e=async()=>{try{let e=(await (0,a.getCallbacksCall)(i,x,c)).router_settings,l=e.model_group_retry_policy,t=e.num_retries;C(l),S(e.retry_policy),E(t);let s=e.model_group_alias||{};F(s)}catch(e){console.error("Error fetching model data:",e)}};i&&o&&c&&x&&Y&&e()},[i,o,c,x,Y]),c&&"Admin Viewer"==c){let{Title:e,Paragraph:l}=Q.default;return(0,s.jsxs)("div",{children:[(0,s.jsx)(e,{level:1,children:"Access Denied"}),(0,s.jsx)(l,{children:"Ask your proxy admin for access to view all models"})]})}let eZ=async()=>{try{let e=await p.validateFields();await eh(e,i,p,eN)}catch(t){var e;let l=(null===(e=t.errorFields)||void 0===e?void 0:e.map(e=>"".concat(e.name.join("."),": ").concat(e.errors.join(", "))).join(" | "))||"Unknown validation error";eo.Z.fromBackend("Please fill in the following required fields: ".concat(l))}};return(Object.keys(L.Cl).find(e=>L.Cl[e]===b),B)?(0,s.jsx)("div",{className:"w-full h-full",children:(0,s.jsx)(l0.Z,{teamId:B,onClose:()=>G(null),accessToken:i,is_team_admin:"Admin"===c,is_proxy_admin:"Proxy Admin"===c,userModels:eu,editTeam:!1,onUpdate:eN,premiumUser:t})}):(0,s.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,s.jsx)(O.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,s.jsxs)(eq.Z,{numColSpan:1,className:"flex flex-col gap-2",children:[(0,s.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,s.jsxs)("div",{children:[(0,s.jsx)("h2",{className:"text-lg font-semibold",children:"Model Management"}),eR.ZL.includes(c)?(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"Add and manage models for the proxy"}):(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"Add models for teams you are an admin for."})]})}),(0,s.jsxs)("div",{className:"mb-4 px-4 py-3 bg-blue-50 rounded-lg border border-blue-100 flex items-center gap-4",children:[(0,s.jsx)("div",{className:"flex-shrink-0 w-10 h-10 bg-white rounded-full flex items-center justify-center border border-blue-200",children:(0,s.jsx)(eU.Z,{style:{fontSize:"18px",color:"#6366f1"}})}),(0,s.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,s.jsx)("h4",{className:"text-gray-900 font-semibold text-sm m-0",children:"Missing a provider?"}),(0,s.jsx)("p",{className:"text-gray-500 text-xs m-0 mt-0.5",children:"The LiteLLM engineering team is constantly adding support for new LLM models, providers, endpoints. If you don't see the one you need, let us know and we'll prioritize it."})]}),(0,s.jsxs)("a",{href:"https://models.litellm.ai/?request=true",target:"_blank",rel:"noopener noreferrer",className:"flex-shrink-0 inline-flex items-center gap-2 px-4 py-2 bg-[#6366f1] hover:bg-[#5558e3] text-white text-sm font-medium rounded-lg transition-colors",children:["Request Provider",(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:(0,s.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})]}),V&&!($||et||ea||en)?(0,s.jsx)(lX,{modelId:V,onClose:()=>{q(null)},accessToken:i,userID:x,userRole:c,onModelUpdate:e=>{W.invalidateQueries({queryKey:["models","list"]}),eN()},modelAccessGroups:ec}):(0,s.jsxs)(eD.Z,{index:U,onIndexChange:H,className:"gap-2 h-[75vh] w-full ",children:[(0,s.jsxs)(eB.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,s.jsxs)("div",{className:"flex",children:[eR.ZL.includes(c)?(0,s.jsx)(ez.Z,{children:"All Models"}):(0,s.jsx)(ez.Z,{children:"Your Models"}),!eb&&(0,s.jsx)(ez.Z,{children:"Add Model"}),eR.ZL.includes(c)&&(0,s.jsx)(ez.Z,{children:"LLM Credentials"}),eR.ZL.includes(c)&&(0,s.jsx)(ez.Z,{children:"Pass-Through Endpoints"}),eR.ZL.includes(c)&&(0,s.jsx)(ez.Z,{children:"Health Status"}),eR.ZL.includes(c)&&(0,s.jsx)(ez.Z,{children:"Model Retry Settings"}),eR.ZL.includes(c)&&(0,s.jsx)(ez.Z,{children:"Model Group Alias"}),eR.ZL.includes(c)&&(0,s.jsx)(ez.Z,{children:"Price Data Reload"})]}),(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[g&&(0,s.jsxs)(D.Z,{children:["Last Refreshed: ",g]}),(0,s.jsx)(P.Z,{icon:eO.Z,variant:"shadow",size:"xs",className:"self-center",onClick:eN})]})]}),(0,s.jsxs)(eG.Z,{children:[(0,s.jsx)(J,{selectedModelGroup:N,setSelectedModelGroup:w,availableModelGroups:ed,availableModelAccessGroups:ec,setSelectedModelId:q,setSelectedTeamId:G}),!eb&&(0,s.jsx)(z.Z,{className:"h-full",children:(0,s.jsx)(lA,{form:p,handleOk:eZ,selectedProvider:b,setSelectedProvider:y,providerModels:v,setProviderModelsFn:e=>{_((0,L.bK)(e,el))},getPlaceholder:L.ph,uploadProps:ey,showAdvancedSettings:I,setShowAdvancedSettings:R,teams:r,credentials:er,accessToken:i,userRole:c})}),(0,s.jsx)(z.Z,{children:(0,s.jsx)(eT,{uploadProps:ey})}),(0,s.jsx)(z.Z,{children:(0,s.jsx)(lQ.Z,{accessToken:i,userRole:c,userID:x,modelData:ep,premiumUser:t})}),(0,s.jsx)(z.Z,{children:(0,s.jsx)(lT,{accessToken:i,modelData:ep,all_models_on_proxy:eu,getDisplayModelName:T,setSelectedModelId:q})}),(0,s.jsx)(X,{selectedModelGroup:N,setSelectedModelGroup:w,availableModelGroups:ed,globalRetryPolicy:k,setGlobalRetryPolicy:S,defaultRetry:A,modelGroupRetryPolicy:Z,setModelGroupRetryPolicy:C,handleSaveRetrySettings:ew}),(0,s.jsx)(z.Z,{children:(0,s.jsx)(lz,{accessToken:i,initialModelGroupAlias:M,onAliasUpdate:F})}),(0,s.jsx)(em,{})]})]})]})})})}},27593:function(e,l,t){t.d(l,{Z:function(){return Y}});var s=t(57437),a=t(2265),r=t(78489),i=t(47323),n=t(84264),o=t(96761),d=t(19250),c=t(99981),m=t(33866),u=t(15731),h=t(53410),x=t(74998),p=t(59341),g=t(49566),f=t(12514),j=t(97765),v=t(37592),_=t(10032),b=t(22116),y=t(51653),N=t(24199),w=t(12660),Z=t(15424),C=t(58760),k=t(5545),S=t(45246),A=t(96473),E=t(31283),P=e=>{let{value:l={},onChange:t}=e,[r,i]=(0,a.useState)(Object.entries(l)),n=e=>{let l=r.filter((l,t)=>t!==e);i(l),null==t||t(Object.fromEntries(l))},o=(e,l,s)=>{let a=[...r];a[e]=[l,s],i(a),null==t||t(Object.fromEntries(a))};return(0,s.jsxs)("div",{children:[r.map((e,l)=>{let[t,a]=e;return(0,s.jsxs)(C.Z,{style:{display:"flex",marginBottom:8},align:"center",children:[(0,s.jsx)(E.o,{placeholder:"Header Name",value:t,onChange:e=>o(l,e.target.value,a)}),(0,s.jsx)(E.o,{placeholder:"Header Value",value:a,onChange:e=>o(l,t,e.target.value)}),(0,s.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,s.jsx)(S.Z,{onClick:()=>n(l),style:{cursor:"pointer"}})})]},l)}),(0,s.jsx)(k.ZP,{type:"dashed",onClick:()=>{i([...r,["",""]])},icon:(0,s.jsx)(A.Z,{}),children:"Add Header"})]})},M=t(77565),L=e=>{let{pathValue:l,targetValue:t,includeSubpath:a}=e,r=(0,d.getProxyBaseUrl)();return l&&t?(0,s.jsxs)(f.Z,{className:"p-5",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Route Preview"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-5",children:"How your requests will be routed"}),(0,s.jsxs)("div",{className:"space-y-5",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"text-base font-semibold text-gray-900 mb-3",children:"Basic routing:"}),(0,s.jsxs)("div",{className:"flex items-center gap-4",children:[(0,s.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,s.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Your endpoint"}),(0,s.jsx)("code",{className:"font-mono text-sm text-gray-900",children:l?"".concat(r).concat(l):""})]}),(0,s.jsx)("div",{className:"text-gray-400",children:(0,s.jsx)(M.Z,{className:"text-lg"})}),(0,s.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,s.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Forwards to"}),(0,s.jsx)("code",{className:"font-mono text-sm text-gray-900",children:t})]})]})]}),a&&(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"text-base font-semibold text-gray-900 mb-3",children:"With subpaths:"}),(0,s.jsxs)("div",{className:"flex items-center gap-4",children:[(0,s.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,s.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Your endpoint + subpath"}),(0,s.jsxs)("code",{className:"font-mono text-sm text-gray-900",children:[l&&"".concat(r).concat(l),(0,s.jsx)("span",{className:"text-blue-600",children:"/v1/text-to-image/base/model"})]})]}),(0,s.jsx)("div",{className:"text-gray-400",children:(0,s.jsx)(M.Z,{className:"text-lg"})}),(0,s.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,s.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Forwards to"}),(0,s.jsxs)("code",{className:"font-mono text-sm text-gray-900",children:[t,(0,s.jsx)("span",{className:"text-blue-600",children:"/v1/text-to-image/base/model"})]})]})]}),(0,s.jsxs)("div",{className:"mt-3 text-sm text-gray-600",children:["Any path after ",l," will be appended to the target URL"]})]})}),!a&&(0,s.jsx)("div",{className:"mt-4 p-3 bg-blue-50 rounded-md border border-blue-200",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(Z.Z,{className:"text-blue-500 mt-0.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{className:"text-sm text-blue-700",children:[(0,s.jsx)("span",{className:"font-medium",children:"Not seeing the routing you wanted?"})," Try enabling - Include Subpaths - above - this allows subroutes like"," ",(0,s.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded font-mono text-xs",children:"/api/v1/models"})," to be forwarded automatically."]})]})})]})]}):null},F=t(9114),I=t(63709),T=e=>{let{premiumUser:l,authEnabled:t,onAuthChange:a}=e;return(0,s.jsxs)(f.Z,{className:"p-6",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Security"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-4",children:"When enabled, requests to this endpoint will require a valid LiteLLM Virtual Key"}),l?(0,s.jsx)(_.Z.Item,{name:"auth",valuePropName:"checked",className:"mb-0",children:(0,s.jsx)(I.Z,{checked:t,onChange:e=>{a(e)}})}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center mb-3",children:[(0,s.jsx)(I.Z,{disabled:!0,checked:!1,style:{outline:"2px solid #d1d5db",outlineOffset:"2px"}}),(0,s.jsx)("span",{className:"ml-2 text-sm text-gray-400",children:"Authentication (Premium)"})]}),(0,s.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,s.jsxs)(n.Z,{className:"text-sm text-yellow-800",children:["Setting authentication for pass-through endpoints is a LiteLLM Enterprise feature. Get a trial key"," ",(0,s.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})]})},R=t(67479),O=e=>{let{accessToken:l,value:t={},onChange:r,disabled:i=!1}=e,[n,d]=(0,a.useState)(Object.keys(t)),[m,u]=(0,a.useState)(t);(0,a.useEffect)(()=>{u(t),d(Object.keys(t))},[t]);let h=(e,l,t)=>{var s,a;let i=m[e]||{},n={...m,[e]:{...i,[l]:t.length>0?t:void 0}};(null===(s=n[e])||void 0===s?void 0:s.request_fields)||(null===(a=n[e])||void 0===a?void 0:a.response_fields)||(n[e]=null),u(n),r&&r(n)};return(0,s.jsxs)(f.Z,{className:"p-6",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Guardrails"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-6",children:"Configure guardrails to enforce policies on requests and responses. Guardrails are opt-in for passthrough endpoints."}),(0,s.jsx)(y.Z,{message:(0,s.jsxs)("span",{children:["Field-Level Targeting"," ",(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through_guardrails#field-level-targeting",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"(Learn More)"})]}),description:(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsx)("div",{children:"Optionally specify which fields to check. If left empty, the entire request/response is sent to the guardrail."}),(0,s.jsxs)("div",{className:"text-xs space-y-1 mt-2",children:[(0,s.jsx)("div",{className:"font-medium",children:"Common Examples:"}),(0,s.jsxs)("div",{children:["• ",(0,s.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"query"})," - Single field"]}),(0,s.jsxs)("div",{children:["• ",(0,s.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"documents[*].text"})," - All text in documents array"]}),(0,s.jsxs)("div",{children:["• ",(0,s.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"messages[*].content"})," - All message contents"]})]})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,s.jsx)(_.Z.Item,{label:(0,s.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Select Guardrails",(0,s.jsx)(c.Z,{title:"Choose which guardrails should run on this endpoint. Org/team/key level guardrails will also be included.",children:(0,s.jsx)(Z.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),children:(0,s.jsx)(R.Z,{accessToken:l,value:n,onChange:e=>{d(e);let l={};e.forEach(e=>{l[e]=m[e]||null}),u(l),r&&r(l)},disabled:i})}),n.length>0&&(0,s.jsxs)("div",{className:"mt-6 space-y-4",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between mb-3",children:[(0,s.jsx)("div",{className:"text-sm font-medium text-gray-700",children:"Field Targeting (Optional)"}),(0,s.jsx)("div",{className:"text-xs text-gray-500",children:"\uD83D\uDCA1 Tip: Leave empty to check entire payload"})]}),n.map(e=>{var l,t;return(0,s.jsxs)(f.Z,{className:"p-4 bg-gray-50",children:[(0,s.jsx)("div",{className:"text-sm font-medium text-gray-900 mb-3",children:e}),(0,s.jsxs)("div",{className:"space-y-3",children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,s.jsxs)("label",{className:"text-xs text-gray-600 flex items-center",children:["Request Fields (pre_call)",(0,s.jsx)(c.Z,{title:(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"font-medium mb-1",children:"Specify which request fields to check"}),(0,s.jsxs)("div",{className:"text-xs space-y-1",children:[(0,s.jsx)("div",{children:"Examples:"}),(0,s.jsx)("div",{children:"• query"}),(0,s.jsx)("div",{children:"• documents[*].text"}),(0,s.jsx)("div",{children:"• messages[*].content"})]})]}),children:(0,s.jsx)(Z.Z,{className:"ml-1 text-gray-400"})})]}),(0,s.jsxs)("div",{className:"flex gap-1",children:[(0,s.jsx)("button",{type:"button",onClick:()=>{var l;let t=(null===(l=m[e])||void 0===l?void 0:l.request_fields)||[];h(e,"request_fields",[...t,"query"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:i,children:"+ query"}),(0,s.jsx)("button",{type:"button",onClick:()=>{var l;let t=(null===(l=m[e])||void 0===l?void 0:l.request_fields)||[];h(e,"request_fields",[...t,"documents[*]"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:i,children:"+ documents[*]"})]})]}),(0,s.jsx)(v.default,{mode:"tags",style:{width:"100%"},placeholder:"Type field name or use + buttons above (e.g., query, documents[*].text)",value:(null===(l=m[e])||void 0===l?void 0:l.request_fields)||[],onChange:l=>h(e,"request_fields",l),disabled:i,tokenSeparators:[","]})]}),(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,s.jsxs)("label",{className:"text-xs text-gray-600 flex items-center",children:["Response Fields (post_call)",(0,s.jsx)(c.Z,{title:(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"font-medium mb-1",children:"Specify which response fields to check"}),(0,s.jsxs)("div",{className:"text-xs space-y-1",children:[(0,s.jsx)("div",{children:"Examples:"}),(0,s.jsx)("div",{children:"• results[*].text"}),(0,s.jsx)("div",{children:"• choices[*].message.content"})]})]}),children:(0,s.jsx)(Z.Z,{className:"ml-1 text-gray-400"})})]}),(0,s.jsx)("div",{className:"flex gap-1",children:(0,s.jsx)("button",{type:"button",onClick:()=>{var l;let t=(null===(l=m[e])||void 0===l?void 0:l.response_fields)||[];h(e,"response_fields",[...t,"results[*]"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:i,children:"+ results[*]"})})]}),(0,s.jsx)(v.default,{mode:"tags",style:{width:"100%"},placeholder:"Type field name or use + buttons above (e.g., results[*].text)",value:(null===(t=m[e])||void 0===t?void 0:t.response_fields)||[],onChange:l=>h(e,"response_fields",l),disabled:i,tokenSeparators:[","]})]})]})]},e)})]})]})};let{Option:V}=v.default;var q=e=>{let{accessToken:l,setPassThroughItems:t,passThroughItems:i,premiumUser:n=!1}=e,[m]=_.Z.useForm(),[u,h]=(0,a.useState)(!1),[x,v]=(0,a.useState)(!1),[C,k]=(0,a.useState)(""),[S,A]=(0,a.useState)(""),[E,M]=(0,a.useState)(""),[I,R]=(0,a.useState)(!0),[V,q]=(0,a.useState)(!1),[z,D]=(0,a.useState)({}),B=()=>{m.resetFields(),A(""),M(""),R(!0),D({}),h(!1)},G=e=>{let l=e;e&&!e.startsWith("/")&&(l="/"+e),A(l),m.setFieldsValue({path:l})},U=async e=>{console.log("addPassThrough called with:",e),v(!0);try{!n&&"auth"in e&&delete e.auth,z&&Object.keys(z).length>0&&(e.guardrails=z),console.log("formValues: ".concat(JSON.stringify(e)));let s=(await (0,d.createPassThroughEndpoint)(l,e)).endpoints[0],a=[...i,s];t(a),F.Z.success("Pass-through endpoint created successfully"),m.resetFields(),A(""),M(""),R(!0),D({}),h(!1)}catch(e){F.Z.fromBackend("Error creating pass-through endpoint: "+e)}finally{v(!1)}};return(0,s.jsxs)("div",{children:[(0,s.jsx)(r.Z,{className:"mx-auto mb-4 mt-4",onClick:()=>h(!0),children:"+ Add Pass-Through Endpoint"}),(0,s.jsx)(b.Z,{title:(0,s.jsxs)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:[(0,s.jsx)(w.Z,{className:"text-xl text-blue-500"}),(0,s.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Pass-Through Endpoint"})]}),open:u,width:1e3,onCancel:B,footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,s.jsxs)("div",{className:"mt-6",children:[(0,s.jsx)(y.Z,{message:"What is a Pass-Through Endpoint?",description:"Route requests from your LiteLLM proxy to any external API. Perfect for custom models, image generation APIs, or any service you want to proxy through LiteLLM.",type:"info",showIcon:!0,className:"mb-6"}),(0,s.jsxs)(_.Z,{form:m,onFinish:U,layout:"vertical",className:"space-y-6",initialValues:{include_subpath:!0,path:S,target:E},children:[(0,s.jsxs)(f.Z,{className:"p-5",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Route Configuration"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-5",children:"Configure how requests to your domain will be forwarded to the target API"}),(0,s.jsxs)("div",{className:"space-y-5",children:[(0,s.jsx)(_.Z.Item,{label:(0,s.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Path Prefix"}),name:"path",rules:[{required:!0,message:"Path is required",pattern:/^\//}],extra:(0,s.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:"Example: /bria, /adobe-photoshop, /elasticsearch"}),className:"mb-4",children:(0,s.jsx)("div",{className:"flex items-center",children:(0,s.jsx)(g.Z,{placeholder:"bria",value:S,onChange:e=>G(e.target.value),className:"flex-1"})})}),(0,s.jsx)(_.Z.Item,{label:(0,s.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Target URL"}),name:"target",rules:[{required:!0,message:"Target URL is required"},{type:"url",message:"Please enter a valid URL"}],extra:(0,s.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:"Example:https://engine.prod.bria-api.com"}),className:"mb-4",children:(0,s.jsx)(g.Z,{placeholder:"https://engine.prod.bria-api.com",value:E,onChange:e=>{M(e.target.value),m.setFieldsValue({target:e.target.value})}})}),(0,s.jsxs)("div",{className:"flex items-center justify-between py-3",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"text-sm font-medium text-gray-700",children:"Include Subpaths"}),(0,s.jsx)("div",{className:"text-xs text-gray-500 mt-0.5",children:"Forward all subpaths to the target API (recommended for REST APIs)"})]}),(0,s.jsx)(_.Z.Item,{name:"include_subpath",valuePropName:"checked",className:"mb-0",children:(0,s.jsx)(p.Z,{checked:I,onChange:R})})]})]})]}),(0,s.jsx)(L,{pathValue:S,targetValue:E,includeSubpath:I}),(0,s.jsxs)(f.Z,{className:"p-6",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Headers"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-6",children:"Add headers that will be sent with every request to the target API"}),(0,s.jsx)(_.Z.Item,{label:(0,s.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Authentication Headers",(0,s.jsx)(c.Z,{title:"Authentication and other headers to forward with requests",children:(0,s.jsx)(Z.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"headers",rules:[{required:!0,message:"Please configure the headers"}],extra:(0,s.jsxs)("div",{className:"text-xs text-gray-500 mt-2",children:[(0,s.jsx)("div",{className:"font-medium mb-1",children:"Add authentication tokens and other required headers"}),(0,s.jsx)("div",{children:"Common examples: auth_token, Authorization, x-api-key"})]}),children:(0,s.jsx)(P,{})})]}),(0,s.jsx)(T,{premiumUser:n,authEnabled:V,onAuthChange:e=>{q(e),m.setFieldsValue({auth:e})}}),(0,s.jsx)(O,{accessToken:l,value:z,onChange:D}),(0,s.jsxs)(f.Z,{className:"p-6",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Billing"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-6",children:"Optional cost tracking for this endpoint"}),(0,s.jsx)(_.Z.Item,{label:(0,s.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Cost Per Request (USD)",(0,s.jsx)(c.Z,{title:"Optional: Track costs for requests to this endpoint",children:(0,s.jsx)(Z.Z,{className:"ml-2 text-gray-400 hover:text-gray-600"})})]}),name:"cost_per_request",extra:(0,s.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"The cost charged for each request through this endpoint"}),children:(0,s.jsx)(N.Z,{min:0,step:.001,precision:4,placeholder:"2.0000",size:"large"})})]}),(0,s.jsxs)("div",{className:"flex items-center justify-end space-x-3 pt-6 border-t border-gray-100",children:[(0,s.jsx)(r.Z,{variant:"secondary",onClick:B,children:"Cancel"}),(0,s.jsx)(r.Z,{variant:"primary",loading:x,onClick:()=>{console.log("Submit button clicked"),m.submit()},children:x?"Creating...":"Add Pass-Through Endpoint"})]})]})]})})]})},z=t(30078),D=t(4260),B=t(12221),G=t(87769),U=t(42208);let H=e=>{let{value:l}=e,[t,r]=(0,a.useState)(!1),i=JSON.stringify(l,null,2);return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("pre",{className:"font-mono text-xs bg-gray-50 p-2 rounded max-w-md overflow-auto",children:t?i:"••••••••"}),(0,s.jsx)("button",{onClick:()=>r(!t),className:"p-1 hover:bg-gray-100 rounded",type:"button",children:t?(0,s.jsx)(G.Z,{className:"w-4 h-4 text-gray-500"}):(0,s.jsx)(U.Z,{className:"w-4 h-4 text-gray-500"})})]})};var K=e=>{let{endpointData:l,onClose:t,accessToken:r,isAdmin:i,premiumUser:n=!1,onEndpointUpdated:o}=e,[c,m]=(0,a.useState)(l),[u,h]=(0,a.useState)(!1),[x,p]=(0,a.useState)(!1),[g,f]=(0,a.useState)((null==l?void 0:l.auth)||!1),[j,v]=(0,a.useState)((null==l?void 0:l.guardrails)||{}),[b]=_.Z.useForm(),y=async e=>{try{if(!r||!(null==c?void 0:c.id))return;let l={};if(e.headers)try{l="string"==typeof e.headers?JSON.parse(e.headers):e.headers}catch(e){F.Z.fromBackend("Invalid JSON format for headers");return}let t={path:c.path,target:e.target,headers:l,include_subpath:e.include_subpath,cost_per_request:e.cost_per_request,auth:n?e.auth:void 0,guardrails:j&&Object.keys(j).length>0?j:void 0};await (0,d.updatePassThroughEndpoint)(r,c.id,t),m({...c,...t}),p(!1),o&&o()}catch(e){console.error("Error updating endpoint:",e),F.Z.fromBackend("Failed to update pass through endpoint")}},N=async()=>{try{if(!r||!(null==c?void 0:c.id))return;await (0,d.deletePassThroughEndpointsCall)(r,c.id),F.Z.success("Pass through endpoint deleted successfully"),t(),o&&o()}catch(e){console.error("Error deleting endpoint:",e),F.Z.fromBackend("Failed to delete pass through endpoint")}};return u?(0,s.jsx)("div",{className:"p-4",children:"Loading..."}):c?(0,s.jsxs)("div",{className:"p-4",children:[(0,s.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,s.jsxs)("div",{children:[(0,s.jsx)(k.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,s.jsxs)(z.Dx,{children:["Pass Through Endpoint: ",c.path]}),(0,s.jsx)(z.xv,{className:"text-gray-500 font-mono",children:c.id})]})}),(0,s.jsxs)(z.v0,{children:[(0,s.jsxs)(z.td,{className:"mb-4",children:[(0,s.jsx)(z.OK,{children:"Overview"},"overview"),i?(0,s.jsx)(z.OK,{children:"Settings"},"settings"):(0,s.jsx)(s.Fragment,{})]}),(0,s.jsxs)(z.nP,{children:[(0,s.jsxs)(z.x4,{children:[(0,s.jsxs)(z.rj,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,s.jsxs)(z.Zb,{children:[(0,s.jsx)(z.xv,{children:"Path"}),(0,s.jsx)("div",{className:"mt-2",children:(0,s.jsx)(z.Dx,{className:"font-mono",children:c.path})})]}),(0,s.jsxs)(z.Zb,{children:[(0,s.jsx)(z.xv,{children:"Target"}),(0,s.jsx)("div",{className:"mt-2",children:(0,s.jsx)(z.Dx,{children:c.target})})]}),(0,s.jsxs)(z.Zb,{children:[(0,s.jsx)(z.xv,{children:"Configuration"}),(0,s.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,s.jsx)("div",{children:(0,s.jsx)(z.Ct,{color:c.include_subpath?"green":"gray",children:c.include_subpath?"Include Subpath":"Exact Path"})}),(0,s.jsx)("div",{children:(0,s.jsx)(z.Ct,{color:c.auth?"blue":"gray",children:c.auth?"Auth Required":"No Auth"})}),void 0!==c.cost_per_request&&(0,s.jsx)("div",{children:(0,s.jsxs)(z.xv,{children:["Cost per request: $",c.cost_per_request]})})]})]})]}),(0,s.jsx)("div",{className:"mt-6",children:(0,s.jsx)(L,{pathValue:c.path,targetValue:c.target,includeSubpath:c.include_subpath||!1})}),c.headers&&Object.keys(c.headers).length>0&&(0,s.jsxs)(z.Zb,{className:"mt-6",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(z.xv,{className:"font-medium",children:"Headers"}),(0,s.jsxs)(z.Ct,{color:"blue",children:[Object.keys(c.headers).length," headers configured"]})]}),(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(H,{value:c.headers})})]}),c.guardrails&&Object.keys(c.guardrails).length>0&&(0,s.jsxs)(z.Zb,{className:"mt-6",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(z.xv,{className:"font-medium",children:"Guardrails"}),(0,s.jsxs)(z.Ct,{color:"purple",children:[Object.keys(c.guardrails).length," guardrails configured"]})]}),(0,s.jsx)("div",{className:"mt-4 space-y-2",children:Object.entries(c.guardrails).map(e=>{let[l,t]=e;return(0,s.jsxs)("div",{className:"p-3 bg-gray-50 rounded",children:[(0,s.jsx)("div",{className:"font-medium text-sm",children:l}),t&&(t.request_fields||t.response_fields)&&(0,s.jsxs)("div",{className:"mt-2 text-xs text-gray-600 space-y-1",children:[t.request_fields&&(0,s.jsxs)("div",{children:["Request fields: ",t.request_fields.join(", ")]}),t.response_fields&&(0,s.jsxs)("div",{children:["Response fields: ",t.response_fields.join(", ")]})]}),!t&&(0,s.jsx)("div",{className:"text-xs text-gray-600 mt-1",children:"Uses entire payload"})]},l)})})]})]}),i&&(0,s.jsx)(z.x4,{children:(0,s.jsxs)(z.Zb,{children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,s.jsx)(z.Dx,{children:"Pass Through Endpoint Settings"}),(0,s.jsx)("div",{className:"space-x-2",children:!x&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(z.zx,{onClick:()=>p(!0),children:"Edit Settings"}),(0,s.jsx)(z.zx,{onClick:N,variant:"secondary",color:"red",children:"Delete Endpoint"})]})})]}),x?(0,s.jsxs)(_.Z,{form:b,onFinish:y,initialValues:{target:c.target,headers:c.headers?JSON.stringify(c.headers,null,2):"",include_subpath:c.include_subpath||!1,cost_per_request:c.cost_per_request,auth:c.auth||!1},layout:"vertical",children:[(0,s.jsx)(_.Z.Item,{label:"Target URL",name:"target",rules:[{required:!0,message:"Please input a target URL"}],children:(0,s.jsx)(z.oi,{placeholder:"https://api.example.com"})}),(0,s.jsx)(_.Z.Item,{label:"Headers (JSON)",name:"headers",children:(0,s.jsx)(D.default.TextArea,{rows:5,placeholder:'{"Authorization": "Bearer your-token", "Content-Type": "application/json"}'})}),(0,s.jsx)(_.Z.Item,{label:"Include Subpath",name:"include_subpath",valuePropName:"checked",children:(0,s.jsx)(I.Z,{})}),(0,s.jsx)(_.Z.Item,{label:"Cost per Request",name:"cost_per_request",children:(0,s.jsx)(B.Z,{min:0,step:.01,precision:2,placeholder:"0.00",addonBefore:"$"})}),(0,s.jsx)(T,{premiumUser:n,authEnabled:g,onAuthChange:e=>{f(e),b.setFieldsValue({auth:e})}}),(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(O,{accessToken:r||"",value:j,onChange:v})}),(0,s.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,s.jsx)(k.ZP,{onClick:()=>p(!1),children:"Cancel"}),(0,s.jsx)(z.zx,{children:"Save Changes"})]})]}):(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(z.xv,{className:"font-medium",children:"Path"}),(0,s.jsx)("div",{className:"font-mono",children:c.path})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(z.xv,{className:"font-medium",children:"Target URL"}),(0,s.jsx)("div",{children:c.target})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(z.xv,{className:"font-medium",children:"Include Subpath"}),(0,s.jsx)(z.Ct,{color:c.include_subpath?"green":"gray",children:c.include_subpath?"Yes":"No"})]}),void 0!==c.cost_per_request&&(0,s.jsxs)("div",{children:[(0,s.jsx)(z.xv,{className:"font-medium",children:"Cost per Request"}),(0,s.jsxs)("div",{children:["$",c.cost_per_request]})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(z.xv,{className:"font-medium",children:"Authentication Required"}),(0,s.jsx)(z.Ct,{color:c.auth?"green":"gray",children:c.auth?"Yes":"No"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(z.xv,{className:"font-medium",children:"Headers"}),c.headers&&Object.keys(c.headers).length>0?(0,s.jsx)("div",{className:"mt-2",children:(0,s.jsx)(H,{value:c.headers})}):(0,s.jsx)("div",{className:"text-gray-500",children:"No headers configured"})]})]})]})})]})]})]}):(0,s.jsx)("div",{className:"p-4",children:"Pass through endpoint not found"})},J=t(12322);let W=e=>{let{value:l}=e,[t,r]=(0,a.useState)(!1),i=JSON.stringify(l);return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("span",{className:"font-mono text-xs",children:t?i:"••••••••"}),(0,s.jsx)("button",{onClick:()=>r(!t),className:"p-1 hover:bg-gray-100 rounded",type:"button",children:t?(0,s.jsx)(G.Z,{className:"w-4 h-4 text-gray-500"}):(0,s.jsx)(U.Z,{className:"w-4 h-4 text-gray-500"})})]})};var Y=e=>{let{accessToken:l,userRole:t,userID:p,modelData:g,premiumUser:f}=e,[j,v]=(0,a.useState)([]),[_,b]=(0,a.useState)(null),[y,N]=(0,a.useState)(!1),[w,Z]=(0,a.useState)(null);(0,a.useEffect)(()=>{l&&t&&p&&(0,d.getPassThroughEndpointsCall)(l).then(e=>{v(e.endpoints)})},[l,t,p]);let C=async e=>{Z(e),N(!0)},k=async()=>{if(null!=w&&l){try{await (0,d.deletePassThroughEndpointsCall)(l,w);let e=j.filter(e=>e.id!==w);v(e),F.Z.success("Endpoint deleted successfully.")}catch(e){console.error("Error deleting the endpoint:",e),F.Z.fromBackend("Error deleting the endpoint: "+e)}N(!1),Z(null)}},S=(e,l)=>{C(e)},A=[{header:"ID",accessorKey:"id",cell:e=>(0,s.jsx)(c.Z,{title:e.row.original.id,children:(0,s.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 max-w-[15ch]",onClick:()=>e.row.original.id&&b(e.row.original.id),children:e.row.original.id})})},{header:"Path",accessorKey:"path"},{header:"Target",accessorKey:"target",cell:e=>(0,s.jsx)(n.Z,{children:e.getValue()})},{header:()=>(0,s.jsxs)("div",{className:"flex items-center gap-1",children:[(0,s.jsx)("span",{children:"Authentication"}),(0,s.jsx)(c.Z,{title:"LiteLLM Virtual Key required to call endpoint",children:(0,s.jsx)(u.Z,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),accessorKey:"auth",cell:e=>(0,s.jsx)(m.Z,{color:e.getValue()?"green":"gray",children:e.getValue()?"Yes":"No"})},{header:"Headers",accessorKey:"headers",cell:e=>(0,s.jsx)(W,{value:e.getValue()||{}})},{header:"Actions",id:"actions",cell:e=>{let{row:l}=e;return(0,s.jsxs)("div",{className:"flex space-x-1",children:[(0,s.jsx)(i.Z,{icon:h.Z,size:"sm",onClick:()=>l.original.id&&b(l.original.id),title:"Edit"}),(0,s.jsx)(i.Z,{icon:x.Z,size:"sm",onClick:()=>S(l.original.id,l.index),title:"Delete"})]})}}];if(!l)return null;if(_){console.log("selectedEndpointId",_),console.log("generalSettings",j);let e=j.find(e=>e.id===_);return e?(0,s.jsx)(K,{endpointData:e,onClose:()=>b(null),accessToken:l,isAdmin:"Admin"===t||"admin"===t,premiumUser:f,onEndpointUpdated:()=>{l&&(0,d.getPassThroughEndpointsCall)(l).then(e=>{v(e.endpoints)})}}):(0,s.jsx)("div",{children:"Endpoint not found"})}return(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(o.Z,{children:"Pass Through Endpoints"}),(0,s.jsx)(n.Z,{className:"text-tremor-content",children:"Configure and manage your pass-through endpoints"})]}),(0,s.jsx)(q,{accessToken:l,setPassThroughItems:v,passThroughItems:j,premiumUser:f}),(0,s.jsx)(J.w,{data:j,columns:A,renderSubComponent:()=>(0,s.jsx)("div",{}),getRowCanExpand:()=>!1,isLoading:!1,noDataMessage:"No pass-through endpoints configured"}),y&&(0,s.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,s.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,s.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,s.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,s.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,s.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,s.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,s.jsx)("div",{className:"sm:flex sm:items-start",children:(0,s.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,s.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Pass-Through Endpoint"}),(0,s.jsx)("div",{className:"mt-2",children:(0,s.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this pass-through endpoint? This action cannot be undone."})})]})})}),(0,s.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,s.jsx)(r.Z,{onClick:k,color:"red",className:"ml-2",children:"Delete"}),(0,s.jsx)(r.Z,{onClick:()=>{N(!1),Z(null)},children:"Cancel"})]})]})]})})]})}},12322:function(e,l,t){t.d(l,{w:function(){return o}});var s=t(57437),a=t(2265),r=t(71594),i=t(24525),n=t(19130);function o(e){let{data:l=[],columns:t,onRowClick:o,renderSubComponent:d,getRowCanExpand:c,isLoading:m=!1,loadingMessage:u="\uD83D\uDE85 Loading logs...",noDataMessage:h="No logs found"}=e,x=!!d&&!!c,p=(0,r.b7)({data:l,columns:t,...x&&{getRowCanExpand:c},getRowId:(e,l)=>{var t;return null!==(t=null==e?void 0:e.request_id)&&void 0!==t?t:String(l)},getCoreRowModel:(0,i.sC)(),...x&&{getExpandedRowModel:(0,i.rV)()}});return(0,s.jsx)("div",{className:"rounded-lg custom-border overflow-x-auto w-full max-w-full box-border",children:(0,s.jsxs)(n.iA,{className:"[&_td]:py-0.5 [&_th]:py-1 table-fixed w-full box-border",style:{minWidth:"400px"},children:[(0,s.jsx)(n.ss,{children:p.getHeaderGroups().map(e=>(0,s.jsx)(n.SC,{children:e.headers.map(e=>(0,s.jsx)(n.xs,{className:"py-1 h-8",children:e.isPlaceholder?null:(0,r.ie)(e.column.columnDef.header,e.getContext())},e.id))},e.id))}),(0,s.jsx)(n.RM,{children:m?(0,s.jsx)(n.SC,{children:(0,s.jsx)(n.pj,{colSpan:t.length,className:"h-8 text-center",children:(0,s.jsx)("div",{className:"text-center text-gray-500",children:(0,s.jsx)("p",{children:u})})})}):p.getRowModel().rows.length>0?p.getRowModel().rows.map(e=>(0,s.jsxs)(a.Fragment,{children:[(0,s.jsx)(n.SC,{className:"h-8 ".concat(x?"":"cursor-pointer hover:bg-gray-50"),onClick:()=>!x&&(null==o?void 0:o(e.original)),children:e.getVisibleCells().map(e=>(0,s.jsx)(n.pj,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,r.ie)(e.column.columnDef.cell,e.getContext())},e.id))}),x&&e.getIsExpanded()&&d&&(0,s.jsx)(n.SC,{children:(0,s.jsx)(n.pj,{colSpan:e.getVisibleCells().length,className:"p-0",children:(0,s.jsx)("div",{className:"w-full max-w-full overflow-hidden box-border",children:d({row:e})})})})]},e.id)):(0,s.jsx)(n.SC,{children:(0,s.jsx)(n.pj,{colSpan:t.length,className:"h-8 text-center",children:(0,s.jsx)("div",{className:"text-center text-gray-500",children:(0,s.jsx)("p",{children:h})})})})})]})})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/7967-1ac5097c3d83016f.js b/litellm/proxy/_experimental/out/_next/static/chunks/1739-08c9b1510314fa66.js similarity index 71% rename from litellm/proxy/_experimental/out/_next/static/chunks/7967-1ac5097c3d83016f.js rename to litellm/proxy/_experimental/out/_next/static/chunks/1739-08c9b1510314fa66.js index 5440aac139c..32836fcc5fb 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/7967-1ac5097c3d83016f.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1739-08c9b1510314fa66.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[7967],{34310:function(e,t,r){"use strict";r.d(t,{Z:function(){return a}});var n=r(1119),i=r(2265),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326zm1.8 562H232V136h302v216a42 42 0 0042 42h216v494zM472 744a40 40 0 1080 0 40 40 0 10-80 0zm16-104h48c4.4 0 8-3.6 8-8V448c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v184c0 4.4 3.6 8 8 8z"}}]},name:"file-exclamation",theme:"outlined"},s=r(55015),a=i.forwardRef(function(e,t){return i.createElement(s.Z,(0,n.Z)({},e,{ref:t,icon:o}))})},38434:function(e,t,r){"use strict";r.d(t,{Z:function(){return a}});var n=r(1119),i=r(2265),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326zm1.8 562H232V136h302v216a42 42 0 0042 42h216v494zM504 618H320c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8zM312 490v48c0 4.4 3.6 8 8 8h384c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H320c-4.4 0-8 3.6-8 8z"}}]},name:"file-text",theme:"outlined"},s=r(55015),a=i.forwardRef(function(e,t){return i.createElement(s.Z,(0,n.Z)({},e,{ref:t,icon:o}))})},3632:function(e,t,r){"use strict";r.d(t,{Z:function(){return a}});var n=r(1119),i=r(2265),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M400 317.7h73.9V656c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V317.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 163a8 8 0 00-12.6 0l-112 141.7c-4.1 5.3-.4 13 6.3 13zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"}}]},name:"upload",theme:"outlined"},s=r(55015),a=i.forwardRef(function(e,t){return i.createElement(s.Z,(0,n.Z)({},e,{ref:t,icon:o}))})},35291:function(e,t,r){"use strict";r.d(t,{Z:function(){return a}});var n=r(1119),i=r(2265),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M464 720a48 48 0 1096 0 48 48 0 10-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"}}]},name:"warning",theme:"outlined"},s=r(55015),a=i.forwardRef(function(e,t){return i.createElement(s.Z,(0,n.Z)({},e,{ref:t,icon:o}))})},30150:function(e,t,r){"use strict";r.d(t,{Z:function(){return f}});var n=r(5853),i=r(2265);let o=e=>{var t=(0,n._T)(e,[]);return i.createElement("svg",Object.assign({},t,{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2.5"}),i.createElement("path",{d:"M12 4v16m8-8H4"}))},s=e=>{var t=(0,n._T)(e,[]);return i.createElement("svg",Object.assign({},t,{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2.5"}),i.createElement("path",{d:"M20 12H4"}))};var a=r(13241),u=r(1153),l=r(69262);let c="flex mx-auto text-tremor-content-subtle dark:text-dark-tremor-content-subtle",d="cursor-pointer hover:text-tremor-content dark:hover:text-dark-tremor-content",f=i.forwardRef((e,t)=>{let{onSubmit:r,enableStepper:f=!0,disabled:h,onValueChange:p,onChange:m}=e,g=(0,n._T)(e,["onSubmit","enableStepper","disabled","onValueChange","onChange"]),v=(0,i.useRef)(null),[y,b]=i.useState(!1),_=i.useCallback(()=>{b(!0)},[]),w=i.useCallback(()=>{b(!1)},[]),[k,E]=i.useState(!1),x=i.useCallback(()=>{E(!0)},[]),C=i.useCallback(()=>{E(!1)},[]);return i.createElement(l.Z,Object.assign({type:"number",ref:(0,u.lq)([v,t]),disabled:h,makeInputClassName:(0,u.fn)("NumberInput"),onKeyDown:e=>{var t;if("Enter"===e.key&&!e.ctrlKey&&!e.altKey&&!e.shiftKey){let e=null===(t=v.current)||void 0===t?void 0:t.value;null==r||r(parseFloat(null!=e?e:""))}"ArrowDown"===e.key&&_(),"ArrowUp"===e.key&&x()},onKeyUp:e=>{"ArrowDown"===e.key&&w(),"ArrowUp"===e.key&&C()},onChange:e=>{h||(null==p||p(parseFloat(e.target.value)),null==m||m(e))},stepper:f?i.createElement("div",{className:(0,a.q)("flex justify-center align-middle")},i.createElement("div",{tabIndex:-1,onClick:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onTouchStart:e=>{e.cancelable&&e.preventDefault()},onMouseUp:()=>{var e,t;h||(null===(e=v.current)||void 0===e||e.stepDown(),null===(t=v.current)||void 0===t||t.dispatchEvent(new Event("input",{bubbles:!0})))},className:(0,a.q)(!h&&d,c,"group py-[10px] px-2.5 border-l border-tremor-border dark:border-dark-tremor-border")},i.createElement(s,{"data-testid":"step-down",className:(y?"scale-95":"")+" h-4 w-4 duration-75 transition group-active:scale-95"})),i.createElement("div",{tabIndex:-1,onClick:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onTouchStart:e=>{e.cancelable&&e.preventDefault()},onMouseUp:()=>{var e,t;h||(null===(e=v.current)||void 0===e||e.stepUp(),null===(t=v.current)||void 0===t||t.dispatchEvent(new Event("input",{bubbles:!0})))},className:(0,a.q)(!h&&d,c,"group py-[10px] px-2.5 border-l border-tremor-border dark:border-dark-tremor-border")},i.createElement(o,{"data-testid":"step-up",className:(k?"scale-95":"")+" h-4 w-4 duration-75 transition group-active:scale-95"}))):null},g))});f.displayName="NumberInput"},87452:function(e,t,r){"use strict";r.d(t,{Z:function(){return d},r:function(){return c}});var n=r(5853),i=r(91054);r(42698),r(64016);var o=r(8710);r(33232);var s=r(13241),a=r(1153),u=r(2265);let l=(0,a.fn)("Accordion"),c=(0,u.createContext)({isOpen:!1}),d=u.forwardRef((e,t)=>{var r;let{defaultOpen:a=!1,children:d,className:f}=e,h=(0,n._T)(e,["defaultOpen","children","className"]),p=null!==(r=(0,u.useContext)(o.Z))&&void 0!==r?r:(0,s.q)("rounded-tremor-default border");return u.createElement(i.pJ,Object.assign({as:"div",ref:t,className:(0,s.q)(l("root"),"overflow-hidden","bg-tremor-background border-tremor-border","dark:bg-dark-tremor-background dark:border-dark-tremor-border",p,f),defaultOpen:a},h),e=>{let{open:t}=e;return u.createElement(c.Provider,{value:{isOpen:t}},d)})});d.displayName="Accordion"},88829:function(e,t,r){"use strict";r.d(t,{Z:function(){return u}});var n=r(5853),i=r(2265),o=r(91054),s=r(13241);let a=(0,r(1153).fn)("AccordionBody"),u=i.forwardRef((e,t)=>{let{children:r,className:u}=e,l=(0,n._T)(e,["children","className"]);return i.createElement(o.pJ.Panel,Object.assign({ref:t,className:(0,s.q)(a("root"),"w-full text-tremor-default px-4 pb-3","text-tremor-content","dark:text-dark-tremor-content",u)},l),r)});u.displayName="AccordionBody"},72208:function(e,t,r){"use strict";r.d(t,{Z:function(){return c}});var n=r(5853),i=r(2265),o=r(91054);let s=e=>{var t=(0,n._T)(e,[]);return i.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},t),i.createElement("path",{d:"M11.9999 10.8284L7.0502 15.7782L5.63599 14.364L11.9999 8L18.3639 14.364L16.9497 15.7782L11.9999 10.8284Z"}))};var a=r(87452),u=r(13241);let l=(0,r(1153).fn)("AccordionHeader"),c=i.forwardRef((e,t)=>{let{children:r,className:c}=e,d=(0,n._T)(e,["children","className"]),{isOpen:f}=(0,i.useContext)(a.r);return i.createElement(o.pJ.Button,Object.assign({ref:t,className:(0,u.q)(l("root"),"w-full flex items-center justify-between px-4 py-3","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis",c)},d),i.createElement("div",{className:(0,u.q)(l("children"),"flex flex-1 text-inherit mr-4")},r),i.createElement("div",null,i.createElement(s,{className:(0,u.q)(l("arrowIcon"),"h-5 w-5 -mr-1","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle",f?"transition-all":"transition-all -rotate-180")})))});c.displayName="AccordionHeader"},23910:function(e,t,r){var n=r(74288).Symbol;e.exports=n},54506:function(e,t,r){var n=r(23910),i=r(4479),o=r(80910),s=n?n.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":s&&s in Object(e)?i(e):o(e)}},55041:function(e,t,r){var n=r(5035),i=/^\s+/;e.exports=function(e){return e?e.slice(0,n(e)+1).replace(i,""):e}},17071:function(e,t,r){var n="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g;e.exports=n},4479:function(e,t,r){var n=r(23910),i=Object.prototype,o=i.hasOwnProperty,s=i.toString,a=n?n.toStringTag:void 0;e.exports=function(e){var t=o.call(e,a),r=e[a];try{e[a]=void 0;var n=!0}catch(e){}var i=s.call(e);return n&&(t?e[a]=r:delete e[a]),i}},80910:function(e){var t=Object.prototype.toString;e.exports=function(e){return t.call(e)}},74288:function(e,t,r){var n=r(17071),i="object"==typeof self&&self&&self.Object===Object&&self,o=n||i||Function("return this")();e.exports=o},5035:function(e){var t=/\s/;e.exports=function(e){for(var r=e.length;r--&&t.test(e.charAt(r)););return r}},7310:function(e,t,r){var n=r(28302),i=r(11121),o=r(6660),s=Math.max,a=Math.min;e.exports=function(e,t,r){var u,l,c,d,f,h,p=0,m=!1,g=!1,v=!0;if("function"!=typeof e)throw TypeError("Expected a function");function y(t){var r=u,n=l;return u=l=void 0,p=t,d=e.apply(n,r)}function b(e){var r=e-h,n=e-p;return void 0===h||r>=t||r<0||g&&n>=c}function _(){var e,r,n,o=i();if(b(o))return w(o);f=setTimeout(_,(e=o-h,r=o-p,n=t-e,g?a(n,c-r):n))}function w(e){return(f=void 0,v&&u)?y(e):(u=l=void 0,d)}function k(){var e,r=i(),n=b(r);if(u=arguments,l=this,h=r,n){if(void 0===f)return p=e=h,f=setTimeout(_,t),m?y(e):d;if(g)return clearTimeout(f),f=setTimeout(_,t),y(h)}return void 0===f&&(f=setTimeout(_,t)),d}return t=o(t)||0,n(r)&&(m=!!r.leading,c=(g="maxWait"in r)?s(o(r.maxWait)||0,t):c,v="trailing"in r?!!r.trailing:v),k.cancel=function(){void 0!==f&&clearTimeout(f),p=0,u=h=l=f=void 0},k.flush=function(){return void 0===f?d:w(i())},k}},28302:function(e){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},10303:function(e){e.exports=function(e){return null!=e&&"object"==typeof e}},78371:function(e,t,r){var n=r(54506),i=r(10303);e.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==n(e)}},11121:function(e,t,r){var n=r(74288);e.exports=function(){return n.Date.now()}},6660:function(e,t,r){var n=r(55041),i=r(28302),o=r(78371),s=0/0,a=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,l=/^0o[0-7]+$/i,c=parseInt;e.exports=function(e){if("number"==typeof e)return e;if(o(e))return s;if(i(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=i(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=n(e);var r=u.test(e);return r||l.test(e)?c(e.slice(2),r?2:8):a.test(e)?s:+e}},79205:function(e,t,r){"use strict";r.d(t,{Z:function(){return d}});var n=r(2265);let i=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),o=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,r)=>r?r.toUpperCase():t.toLowerCase()),s=e=>{let t=o(e);return t.charAt(0).toUpperCase()+t.slice(1)},a=function(){for(var e=arguments.length,t=Array(e),r=0;r!!e&&""!==e.trim()&&r.indexOf(e)===t).join(" ").trim()},u=e=>{for(let t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0};var l={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};let c=(0,n.forwardRef)((e,t)=>{let{color:r="currentColor",size:i=24,strokeWidth:o=2,absoluteStrokeWidth:s,className:c="",children:d,iconNode:f,...h}=e;return(0,n.createElement)("svg",{ref:t,...l,width:i,height:i,stroke:r,strokeWidth:s?24*Number(o)/Number(i):o,className:a("lucide",c),...!d&&!u(h)&&{"aria-hidden":"true"},...h},[...f.map(e=>{let[t,r]=e;return(0,n.createElement)(t,r)}),...Array.isArray(d)?d:[d]])}),d=(e,t)=>{let r=(0,n.forwardRef)((r,o)=>{let{className:u,...l}=r;return(0,n.createElement)(c,{ref:o,iconNode:t,className:a("lucide-".concat(i(s(e))),"lucide-".concat(e),u),...l})});return r.displayName=s(e),r}},30401:function(e,t,r){"use strict";r.d(t,{Z:function(){return n}});let n=(0,r(79205).Z)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]])},78867:function(e,t,r){"use strict";r.d(t,{Z:function(){return n}});let n=(0,r(79205).Z)("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]])},15452:function(e,t){var r,n,i;n=[],void 0!==(i="function"==typeof(r=function e(){var t,r="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==r?r:{},n=!r.document&&!!r.postMessage,i=r.IS_PAPA_WORKER||!1,o={},s=0,a={};function u(e){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(e){var t=b(e);t.chunkSize=parseInt(t.chunkSize),e.step||e.chunk||(t.chunkSize=null),this._handle=new h(t),(this._handle.streamer=this)._config=t}).call(this,e),this.parseChunk=function(e,t){var n=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview,i)r.postMessage({results:o,workerId:a.WORKER_ID,finished:n});else if(w(this._config.chunk)&&!t){if(this._config.chunk(o,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=o=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(o.data),this._completeResults.errors=this._completeResults.errors.concat(o.errors),this._completeResults.meta=o.meta),this._completed||!n||!w(this._config.complete)||o&&o.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),n||o&&o.meta.paused||this._nextChunk(),o}this._halted=!0},this._sendError=function(e){w(this._config.error)?this._config.error(e):i&&this._config.error&&r.postMessage({workerId:a.WORKER_ID,error:e,finished:!1})}}function l(e){var t;(e=e||{}).chunkSize||(e.chunkSize=a.RemoteChunkSize),u.call(this,e),this._nextChunk=n?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(e){this._input=e,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(t=new XMLHttpRequest,this._config.withCredentials&&(t.withCredentials=this._config.withCredentials),n||(t.onload=_(this._chunkLoaded,this),t.onerror=_(this._chunkError,this)),t.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var e,r,i=this._config.downloadRequestHeaders;for(r in i)t.setRequestHeader(r,i[r])}this._config.chunkSize&&(e=this._start+this._config.chunkSize-1,t.setRequestHeader("Range","bytes="+this._start+"-"+e));try{t.send(this._config.downloadRequestBody)}catch(e){this._chunkError(e.message)}n&&0===t.status&&this._chunkError()}},this._chunkLoaded=function(){let e;4===t.readyState&&(t.status<200||400<=t.status?this._chunkError():(this._start+=this._config.chunkSize||t.responseText.length,this._finished=!this._config.chunkSize||this._start>=(null!==(e=(e=t).getResponseHeader("Content-Range"))?parseInt(e.substring(e.lastIndexOf("/")+1)):-1),this.parseChunk(t.responseText)))},this._chunkError=function(e){e=t.statusText||e,this._sendError(Error(e))}}function c(e){(e=e||{}).chunkSize||(e.chunkSize=a.LocalChunkSize),u.call(this,e);var t,r,n="undefined"!=typeof FileReader;this.stream=function(e){this._input=e,r=e.slice||e.webkitSlice||e.mozSlice,n?((t=new FileReader).onload=_(this._chunkLoaded,this),t.onerror=_(this._chunkError,this)):t=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(e.target.result)},this._chunkError=function(){this._sendError(t.error)}}function d(e){var t;u.call(this,e=e||{}),this.stream=function(e){return t=e,this._nextChunk()},this._nextChunk=function(){var e,r;if(!this._finished)return t=(e=this._config.chunkSize)?(r=t.substring(0,e),t.substring(e)):(r=t,""),this._finished=!t,this.parseChunk(r)}}function f(e){u.call(this,e=e||{});var t=[],r=!0,n=!1;this.pause=function(){u.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){u.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(e){this._input=e,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){n&&1===t.length&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),t.length?this.parseChunk(t.shift()):r=!0},this._streamData=_(function(e){try{t.push("string"==typeof e?e:e.toString(this._config.encoding)),r&&(r=!1,this._checkIsFinished(),this.parseChunk(t.shift()))}catch(e){this._streamError(e)}},this),this._streamError=_(function(e){this._streamCleanUp(),this._sendError(e)},this),this._streamEnd=_(function(){this._streamCleanUp(),n=!0,this._streamData("")},this),this._streamCleanUp=_(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function h(e){var t,r,n,i,o=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,s=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,u=this,l=0,c=0,d=!1,f=!1,h=[],g={data:[],errors:[],meta:{}};function v(t){return"greedy"===e.skipEmptyLines?""===t.join("").trim():1===t.length&&0===t[0].length}function y(){if(g&&n&&(k("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),n=!1),e.skipEmptyLines&&(g.data=g.data.filter(function(e){return!v(e)})),_()){if(g){if(Array.isArray(g.data[0])){for(var t,r=0;_()&&r=h.length?"__parsed_extra":h[i]:a,l=u=e.transform?e.transform(u,a):u,(e.dynamicTypingFunction&&void 0===e.dynamicTyping[r]&&(e.dynamicTyping[r]=e.dynamicTypingFunction(r)),!0===(e.dynamicTyping[r]||e.dynamicTyping))?"true"===l||"TRUE"===l||"false"!==l&&"FALSE"!==l&&((e=>{if(o.test(e)&&-9007199254740992<(e=parseFloat(e))&&e<9007199254740992)return 1})(l)?parseFloat(l):s.test(l)?new Date(l):""===l?null:l):l);"__parsed_extra"===a?(n[a]=n[a]||[],n[a].push(u)):n[a]=u}return e.header&&(i>h.length?k("FieldMismatch","TooManyFields","Too many fields: expected "+h.length+" fields but parsed "+i,c+r):ie.preview?r.abort():(g.data=g.data[0],i(g,u))))}),this.parse=function(i,o,s){var u=e.quoteChar||'"',u=(e.newline||(e.newline=this.guessLineEndings(i,u)),n=!1,e.delimiter?w(e.delimiter)&&(e.delimiter=e.delimiter(i),g.meta.delimiter=e.delimiter):((u=((t,r,n,i,o)=>{var s,u,l,c;o=o||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var d=0;d=r.length/2?"\r\n":"\r"}}function p(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function m(e){var t=(e=e||{}).delimiter,r=e.newline,n=e.comments,i=e.step,o=e.preview,s=e.fastMode,u=null,l=!1,c=null==e.quoteChar?'"':e.quoteChar,d=c;if(void 0!==e.escapeChar&&(d=e.escapeChar),("string"!=typeof t||-1=o)return N(!0);break}x.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:E.length,index:f}),D++}}else if(n&&0===C.length&&a.substring(f,f+_)===n){if(-1===T)return N();f=T+b,T=a.indexOf(r,f),j=a.indexOf(t,f)}else if(-1!==j&&(j=o)return N(!0)}return M();function P(e){E.push(e),O=f}function A(e){return -1!==e&&(e=a.substring(D+1,e))&&""===e.trim()?e.length:0}function M(e){return g||(void 0===e&&(e=a.substring(f)),C.push(e),f=v,P(C),k&&F()),N()}function z(e){f=e,P(C),C=[],T=a.indexOf(r,f)}function N(n){if(e.header&&!m&&E.length&&!l){var i=E[0],o=Object.create(null),s=new Set(i);let t=!1;for(let r=0;r{if("object"==typeof t){if("string"!=typeof t.delimiter||a.BAD_DELIMITERS.filter(function(e){return -1!==t.delimiter.indexOf(e)}).length||(i=t.delimiter),("boolean"==typeof t.quotes||"function"==typeof t.quotes||Array.isArray(t.quotes))&&(r=t.quotes),"boolean"!=typeof t.skipEmptyLines&&"string"!=typeof t.skipEmptyLines||(l=t.skipEmptyLines),"string"==typeof t.newline&&(o=t.newline),"string"==typeof t.quoteChar&&(s=t.quoteChar),"boolean"==typeof t.header&&(n=t.header),Array.isArray(t.columns)){if(0===t.columns.length)throw Error("Option columns is empty");c=t.columns}void 0!==t.escapeChar&&(u=t.escapeChar+s),t.escapeFormulae instanceof RegExp?d=t.escapeFormulae:"boolean"==typeof t.escapeFormulae&&t.escapeFormulae&&(d=/^[=+\-@\t\r].*$/)}})(),RegExp(p(s),"g"));if("string"==typeof e&&(e=JSON.parse(e)),Array.isArray(e)){if(!e.length||Array.isArray(e[0]))return h(null,e,l);if("object"==typeof e[0])return h(c||Object.keys(e[0]),e,l)}else if("object"==typeof e)return"string"==typeof e.data&&(e.data=JSON.parse(e.data)),Array.isArray(e.data)&&(e.fields||(e.fields=e.meta&&e.meta.fields||c),e.fields||(e.fields=Array.isArray(e.data[0])?e.fields:"object"==typeof e.data[0]?Object.keys(e.data[0]):[]),Array.isArray(e.data[0])||"object"==typeof e.data[0]||(e.data=[e.data])),h(e.fields||[],e.data||[],l);throw Error("Unable to serialize unrecognized input");function h(e,t,r){var s="",a=("string"==typeof e&&(e=JSON.parse(e)),"string"==typeof t&&(t=JSON.parse(t)),Array.isArray(e)&&0{for(var r=0;r=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}(e,s),n=i.default.Children.only(t);return i.default.cloneElement(n,l(l({},r),{},{onClick:this.onClick}))}}],function(e,t){for(var r=0;r({...e,disclosureState:(0,v.E)(e.disclosureState,{0:1,1:0})}),1:e=>1===e.disclosureState?e:{...e,disclosureState:1},2:(e,t)=>e.buttonId===t.buttonId?e:{...e,buttonId:t.buttonId},3:(e,t)=>e.panelId===t.panelId?e:{...e,panelId:t.panelId},4:(e,t)=>e.buttonElement===t.element?e:{...e,buttonElement:t.element},5:(e,t)=>e.panelElement===t.element?e:{...e,panelElement:t.element}},C=(0,u.createContext)(null);function O(e){let t=(0,u.useContext)(C);if(null===t){let t=Error("<".concat(e," /> is missing a parent component."));throw Error.captureStackTrace&&Error.captureStackTrace(t,O),t}return t}C.displayName="DisclosureContext";let S=(0,u.createContext)(null);S.displayName="DisclosureAPIContext";let R=(0,u.createContext)(null);function j(e,t){return(0,v.E)(t.type,x,e,t)}R.displayName="DisclosurePanelContext";let T=u.Fragment,I=b.VN.RenderStrategy|b.VN.Static,D=Object.assign((0,b.yV)(function(e,t){let{defaultOpen:r=!1,...n}=e,i=(0,u.useRef)(null),o=(0,f.T)(t,(0,f.h)(e=>{i.current=e},void 0===e.as||e.as===u.Fragment)),s=(0,u.useReducer)(j,{disclosureState:r?0:1,buttonElement:null,panelElement:null,buttonId:null,panelId:null}),[{disclosureState:a,buttonId:l},d]=s,h=(0,c.z)(e=>{d({type:1});let t=(0,y.r)(i);if(!t||!l)return;let r=e?e instanceof HTMLElement?e:e.current instanceof HTMLElement?e.current:t.getElementById(l):t.getElementById(l);null==r||r.focus()}),g=(0,u.useMemo)(()=>({close:h}),[h]),_=(0,u.useMemo)(()=>({open:0===a,close:h}),[a,h]),w=(0,b.L6)();return u.createElement(C.Provider,{value:s},u.createElement(S.Provider,{value:g},u.createElement(p.Z,{value:h},u.createElement(m.up,{value:(0,v.E)(a,{0:m.ZM.Open,1:m.ZM.Closed})},w({ourProps:{ref:o},theirProps:n,slot:_,defaultTag:T,name:"Disclosure"})))))}),{Button:(0,b.yV)(function(e,t){let r=(0,u.useId)(),{id:n="headlessui-disclosure-button-".concat(r),disabled:i=!1,autoFocus:o=!1,...h}=e,[p,m]=O("Disclosure.Button"),v=(0,u.useContext)(R),y=null!==v&&v===p.panelId,_=(0,u.useRef)(null),k=(0,f.T)(_,t,(0,c.z)(e=>{if(!y)return m({type:4,element:e})}));(0,u.useEffect)(()=>{if(!y)return m({type:2,buttonId:n}),()=>{m({type:2,buttonId:null})}},[n,m,y]);let E=(0,c.z)(e=>{var t;if(y){if(1===p.disclosureState)return;switch(e.key){case w.R.Space:case w.R.Enter:e.preventDefault(),e.stopPropagation(),m({type:0}),null==(t=p.buttonElement)||t.focus()}}else switch(e.key){case w.R.Space:case w.R.Enter:e.preventDefault(),e.stopPropagation(),m({type:0})}}),x=(0,c.z)(e=>{e.key===w.R.Space&&e.preventDefault()}),C=(0,c.z)(e=>{var t;(0,g.P)(e.currentTarget)||i||(y?(m({type:0}),null==(t=p.buttonElement)||t.focus()):m({type:0}))}),{isFocusVisible:S,focusProps:j}=(0,s.F)({autoFocus:o}),{isHovered:T,hoverProps:I}=(0,a.X)({isDisabled:i}),{pressed:D,pressProps:L}=(0,l.x)({disabled:i}),P=(0,u.useMemo)(()=>({open:0===p.disclosureState,hover:T,active:D,disabled:i,focus:S,autofocus:o}),[p,T,D,S,i,o]),A=(0,d.f)(e,p.buttonElement),M=y?(0,b.dG)({ref:k,type:A,disabled:i||void 0,autoFocus:o,onKeyDown:E,onClick:C},j,I,L):(0,b.dG)({ref:k,id:n,type:A,"aria-expanded":0===p.disclosureState,"aria-controls":p.panelElement?p.panelId:void 0,disabled:i||void 0,autoFocus:o,onKeyDown:E,onKeyUp:x,onClick:C},j,I,L);return(0,b.L6)()({ourProps:M,theirProps:h,slot:P,defaultTag:"button",name:"Disclosure.Button"})}),Panel:(0,b.yV)(function(e,t){let r=(0,u.useId)(),{id:n="headlessui-disclosure-panel-".concat(r),transition:i=!1,...o}=e,[s,a]=O("Disclosure.Panel"),{close:l}=function e(t){let r=(0,u.useContext)(S);if(null===r){let r=Error("<".concat(t," /> is missing a parent component."));throw Error.captureStackTrace&&Error.captureStackTrace(r,e),r}return r}("Disclosure.Panel"),[d,p]=(0,u.useState)(null),g=(0,f.T)(t,(0,c.z)(e=>{_(()=>a({type:5,element:e}))}),p);(0,u.useEffect)(()=>(a({type:3,panelId:n}),()=>{a({type:3,panelId:null})}),[n,a]);let v=(0,m.oJ)(),[y,w]=(0,h.Y)(i,d,null!==v?(v&m.ZM.Open)===m.ZM.Open:0===s.disclosureState),k=(0,u.useMemo)(()=>({open:0===s.disclosureState,close:l}),[s.disclosureState,l]),E={ref:g,id:n,...(0,h.X)(w)},x=(0,b.L6)();return u.createElement(m.uu,null,u.createElement(R.Provider,{value:s.panelId},x({ourProps:E,theirProps:o,slot:k,defaultTag:"div",features:I,visible:y,name:"Disclosure.Panel"})))})})},33443:function(e,t,r){"use strict";r.d(t,{Z:function(){return o}});var n=r(2265);let i=(0,n.createContext)(()=>{});function o(e){let{value:t,children:r}=e;return n.createElement(i.Provider,{value:t},r)}}}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1739],{34310:function(e,t,r){"use strict";r.d(t,{Z:function(){return a}});var n=r(1119),i=r(2265),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326zm1.8 562H232V136h302v216a42 42 0 0042 42h216v494zM472 744a40 40 0 1080 0 40 40 0 10-80 0zm16-104h48c4.4 0 8-3.6 8-8V448c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v184c0 4.4 3.6 8 8 8z"}}]},name:"file-exclamation",theme:"outlined"},s=r(55015),a=i.forwardRef(function(e,t){return i.createElement(s.Z,(0,n.Z)({},e,{ref:t,icon:o}))})},38434:function(e,t,r){"use strict";r.d(t,{Z:function(){return a}});var n=r(1119),i=r(2265),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326zm1.8 562H232V136h302v216a42 42 0 0042 42h216v494zM504 618H320c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8zM312 490v48c0 4.4 3.6 8 8 8h384c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H320c-4.4 0-8 3.6-8 8z"}}]},name:"file-text",theme:"outlined"},s=r(55015),a=i.forwardRef(function(e,t){return i.createElement(s.Z,(0,n.Z)({},e,{ref:t,icon:o}))})},3632:function(e,t,r){"use strict";r.d(t,{Z:function(){return a}});var n=r(1119),i=r(2265),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M400 317.7h73.9V656c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V317.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 163a8 8 0 00-12.6 0l-112 141.7c-4.1 5.3-.4 13 6.3 13zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"}}]},name:"upload",theme:"outlined"},s=r(55015),a=i.forwardRef(function(e,t){return i.createElement(s.Z,(0,n.Z)({},e,{ref:t,icon:o}))})},35291:function(e,t,r){"use strict";r.d(t,{Z:function(){return a}});var n=r(1119),i=r(2265),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M464 720a48 48 0 1096 0 48 48 0 10-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"}}]},name:"warning",theme:"outlined"},s=r(55015),a=i.forwardRef(function(e,t){return i.createElement(s.Z,(0,n.Z)({},e,{ref:t,icon:o}))})},30150:function(e,t,r){"use strict";r.d(t,{Z:function(){return d}});var n=r(5853),i=r(2265);let o=e=>{var t=(0,n._T)(e,[]);return i.createElement("svg",Object.assign({},t,{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2.5"}),i.createElement("path",{d:"M12 4v16m8-8H4"}))},s=e=>{var t=(0,n._T)(e,[]);return i.createElement("svg",Object.assign({},t,{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2.5"}),i.createElement("path",{d:"M20 12H4"}))};var a=r(13241),u=r(1153),l=r(69262);let c="flex mx-auto text-tremor-content-subtle dark:text-dark-tremor-content-subtle",f="cursor-pointer hover:text-tremor-content dark:hover:text-dark-tremor-content",d=i.forwardRef((e,t)=>{let{onSubmit:r,enableStepper:d=!0,disabled:h,onValueChange:p,onChange:m}=e,g=(0,n._T)(e,["onSubmit","enableStepper","disabled","onValueChange","onChange"]),v=(0,i.useRef)(null),[y,b]=i.useState(!1),_=i.useCallback(()=>{b(!0)},[]),w=i.useCallback(()=>{b(!1)},[]),[k,E]=i.useState(!1),x=i.useCallback(()=>{E(!0)},[]),C=i.useCallback(()=>{E(!1)},[]);return i.createElement(l.Z,Object.assign({type:"number",ref:(0,u.lq)([v,t]),disabled:h,makeInputClassName:(0,u.fn)("NumberInput"),onKeyDown:e=>{var t;if("Enter"===e.key&&!e.ctrlKey&&!e.altKey&&!e.shiftKey){let e=null===(t=v.current)||void 0===t?void 0:t.value;null==r||r(parseFloat(null!=e?e:""))}"ArrowDown"===e.key&&_(),"ArrowUp"===e.key&&x()},onKeyUp:e=>{"ArrowDown"===e.key&&w(),"ArrowUp"===e.key&&C()},onChange:e=>{h||(null==p||p(parseFloat(e.target.value)),null==m||m(e))},stepper:d?i.createElement("div",{className:(0,a.q)("flex justify-center align-middle")},i.createElement("div",{tabIndex:-1,onClick:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onTouchStart:e=>{e.cancelable&&e.preventDefault()},onMouseUp:()=>{var e,t;h||(null===(e=v.current)||void 0===e||e.stepDown(),null===(t=v.current)||void 0===t||t.dispatchEvent(new Event("input",{bubbles:!0})))},className:(0,a.q)(!h&&f,c,"group py-[10px] px-2.5 border-l border-tremor-border dark:border-dark-tremor-border")},i.createElement(s,{"data-testid":"step-down",className:(y?"scale-95":"")+" h-4 w-4 duration-75 transition group-active:scale-95"})),i.createElement("div",{tabIndex:-1,onClick:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onTouchStart:e=>{e.cancelable&&e.preventDefault()},onMouseUp:()=>{var e,t;h||(null===(e=v.current)||void 0===e||e.stepUp(),null===(t=v.current)||void 0===t||t.dispatchEvent(new Event("input",{bubbles:!0})))},className:(0,a.q)(!h&&f,c,"group py-[10px] px-2.5 border-l border-tremor-border dark:border-dark-tremor-border")},i.createElement(o,{"data-testid":"step-up",className:(k?"scale-95":"")+" h-4 w-4 duration-75 transition group-active:scale-95"}))):null},g))});d.displayName="NumberInput"},87452:function(e,t,r){"use strict";r.d(t,{Z:function(){return f},r:function(){return c}});var n=r(5853),i=r(91054);r(42698),r(64016);var o=r(8710);r(33232);var s=r(13241),a=r(1153),u=r(2265);let l=(0,a.fn)("Accordion"),c=(0,u.createContext)({isOpen:!1}),f=u.forwardRef((e,t)=>{var r;let{defaultOpen:a=!1,children:f,className:d}=e,h=(0,n._T)(e,["defaultOpen","children","className"]),p=null!==(r=(0,u.useContext)(o.Z))&&void 0!==r?r:(0,s.q)("rounded-tremor-default border");return u.createElement(i.pJ,Object.assign({as:"div",ref:t,className:(0,s.q)(l("root"),"overflow-hidden","bg-tremor-background border-tremor-border","dark:bg-dark-tremor-background dark:border-dark-tremor-border",p,d),defaultOpen:a},h),e=>{let{open:t}=e;return u.createElement(c.Provider,{value:{isOpen:t}},f)})});f.displayName="Accordion"},88829:function(e,t,r){"use strict";r.d(t,{Z:function(){return u}});var n=r(5853),i=r(2265),o=r(91054),s=r(13241);let a=(0,r(1153).fn)("AccordionBody"),u=i.forwardRef((e,t)=>{let{children:r,className:u}=e,l=(0,n._T)(e,["children","className"]);return i.createElement(o.pJ.Panel,Object.assign({ref:t,className:(0,s.q)(a("root"),"w-full text-tremor-default px-4 pb-3","text-tremor-content","dark:text-dark-tremor-content",u)},l),r)});u.displayName="AccordionBody"},72208:function(e,t,r){"use strict";r.d(t,{Z:function(){return c}});var n=r(5853),i=r(2265),o=r(91054);let s=e=>{var t=(0,n._T)(e,[]);return i.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},t),i.createElement("path",{d:"M11.9999 10.8284L7.0502 15.7782L5.63599 14.364L11.9999 8L18.3639 14.364L16.9497 15.7782L11.9999 10.8284Z"}))};var a=r(87452),u=r(13241);let l=(0,r(1153).fn)("AccordionHeader"),c=i.forwardRef((e,t)=>{let{children:r,className:c}=e,f=(0,n._T)(e,["children","className"]),{isOpen:d}=(0,i.useContext)(a.r);return i.createElement(o.pJ.Button,Object.assign({ref:t,className:(0,u.q)(l("root"),"w-full flex items-center justify-between px-4 py-3","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis",c)},f),i.createElement("div",{className:(0,u.q)(l("children"),"flex flex-1 text-inherit mr-4")},r),i.createElement("div",null,i.createElement(s,{className:(0,u.q)(l("arrowIcon"),"h-5 w-5 -mr-1","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle",d?"transition-all":"transition-all -rotate-180")})))});c.displayName="AccordionHeader"},23910:function(e,t,r){var n=r(74288).Symbol;e.exports=n},54506:function(e,t,r){var n=r(23910),i=r(4479),o=r(80910),s=n?n.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":s&&s in Object(e)?i(e):o(e)}},41087:function(e,t,r){var n=r(5035),i=/^\s+/;e.exports=function(e){return e?e.slice(0,n(e)+1).replace(i,""):e}},17071:function(e,t,r){var n="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g;e.exports=n},4479:function(e,t,r){var n=r(23910),i=Object.prototype,o=i.hasOwnProperty,s=i.toString,a=n?n.toStringTag:void 0;e.exports=function(e){var t=o.call(e,a),r=e[a];try{e[a]=void 0;var n=!0}catch(e){}var i=s.call(e);return n&&(t?e[a]=r:delete e[a]),i}},80910:function(e){var t=Object.prototype.toString;e.exports=function(e){return t.call(e)}},74288:function(e,t,r){var n=r(17071),i="object"==typeof self&&self&&self.Object===Object&&self,o=n||i||Function("return this")();e.exports=o},5035:function(e){var t=/\s/;e.exports=function(e){for(var r=e.length;r--&&t.test(e.charAt(r)););return r}},7310:function(e,t,r){var n=r(28302),i=r(11121),o=r(6660),s=Math.max,a=Math.min;e.exports=function(e,t,r){var u,l,c,f,d,h,p=0,m=!1,g=!1,v=!0;if("function"!=typeof e)throw TypeError("Expected a function");function y(t){var r=u,n=l;return u=l=void 0,p=t,f=e.apply(n,r)}function b(e){var r=e-h,n=e-p;return void 0===h||r>=t||r<0||g&&n>=c}function _(){var e,r,n,o=i();if(b(o))return w(o);d=setTimeout(_,(e=o-h,r=o-p,n=t-e,g?a(n,c-r):n))}function w(e){return(d=void 0,v&&u)?y(e):(u=l=void 0,f)}function k(){var e,r=i(),n=b(r);if(u=arguments,l=this,h=r,n){if(void 0===d)return p=e=h,d=setTimeout(_,t),m?y(e):f;if(g)return clearTimeout(d),d=setTimeout(_,t),y(h)}return void 0===d&&(d=setTimeout(_,t)),f}return t=o(t)||0,n(r)&&(m=!!r.leading,c=(g="maxWait"in r)?s(o(r.maxWait)||0,t):c,v="trailing"in r?!!r.trailing:v),k.cancel=function(){void 0!==d&&clearTimeout(d),p=0,u=h=l=d=void 0},k.flush=function(){return void 0===d?f:w(i())},k}},28302:function(e){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},10303:function(e){e.exports=function(e){return null!=e&&"object"==typeof e}},78371:function(e,t,r){var n=r(54506),i=r(10303);e.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==n(e)}},11121:function(e,t,r){var n=r(74288);e.exports=function(){return n.Date.now()}},6660:function(e,t,r){var n=r(41087),i=r(28302),o=r(78371),s=0/0,a=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,l=/^0o[0-7]+$/i,c=parseInt;e.exports=function(e){if("number"==typeof e)return e;if(o(e))return s;if(i(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=i(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=n(e);var r=u.test(e);return r||l.test(e)?c(e.slice(2),r?2:8):a.test(e)?s:+e}},79205:function(e,t,r){"use strict";r.d(t,{Z:function(){return f}});var n=r(2265);let i=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),o=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,r)=>r?r.toUpperCase():t.toLowerCase()),s=e=>{let t=o(e);return t.charAt(0).toUpperCase()+t.slice(1)},a=function(){for(var e=arguments.length,t=Array(e),r=0;r!!e&&""!==e.trim()&&r.indexOf(e)===t).join(" ").trim()},u=e=>{for(let t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0};var l={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};let c=(0,n.forwardRef)((e,t)=>{let{color:r="currentColor",size:i=24,strokeWidth:o=2,absoluteStrokeWidth:s,className:c="",children:f,iconNode:d,...h}=e;return(0,n.createElement)("svg",{ref:t,...l,width:i,height:i,stroke:r,strokeWidth:s?24*Number(o)/Number(i):o,className:a("lucide",c),...!f&&!u(h)&&{"aria-hidden":"true"},...h},[...d.map(e=>{let[t,r]=e;return(0,n.createElement)(t,r)}),...Array.isArray(f)?f:[f]])}),f=(e,t)=>{let r=(0,n.forwardRef)((r,o)=>{let{className:u,...l}=r;return(0,n.createElement)(c,{ref:o,iconNode:t,className:a("lucide-".concat(i(s(e))),"lucide-".concat(e),u),...l})});return r.displayName=s(e),r}},30401:function(e,t,r){"use strict";r.d(t,{Z:function(){return n}});let n=(0,r(79205).Z)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]])},78867:function(e,t,r){"use strict";r.d(t,{Z:function(){return n}});let n=(0,r(79205).Z)("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]])},15452:function(e,t){var r,n,i;n=[],void 0!==(i="function"==typeof(r=function e(){var t,r="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==r?r:{},n=!r.document&&!!r.postMessage,i=r.IS_PAPA_WORKER||!1,o={},s=0,a={};function u(e){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(e){var t=b(e);t.chunkSize=parseInt(t.chunkSize),e.step||e.chunk||(t.chunkSize=null),this._handle=new h(t),(this._handle.streamer=this)._config=t}).call(this,e),this.parseChunk=function(e,t){var n=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview,i)r.postMessage({results:o,workerId:a.WORKER_ID,finished:n});else if(w(this._config.chunk)&&!t){if(this._config.chunk(o,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=o=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(o.data),this._completeResults.errors=this._completeResults.errors.concat(o.errors),this._completeResults.meta=o.meta),this._completed||!n||!w(this._config.complete)||o&&o.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),n||o&&o.meta.paused||this._nextChunk(),o}this._halted=!0},this._sendError=function(e){w(this._config.error)?this._config.error(e):i&&this._config.error&&r.postMessage({workerId:a.WORKER_ID,error:e,finished:!1})}}function l(e){var t;(e=e||{}).chunkSize||(e.chunkSize=a.RemoteChunkSize),u.call(this,e),this._nextChunk=n?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(e){this._input=e,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(t=new XMLHttpRequest,this._config.withCredentials&&(t.withCredentials=this._config.withCredentials),n||(t.onload=_(this._chunkLoaded,this),t.onerror=_(this._chunkError,this)),t.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var e,r,i=this._config.downloadRequestHeaders;for(r in i)t.setRequestHeader(r,i[r])}this._config.chunkSize&&(e=this._start+this._config.chunkSize-1,t.setRequestHeader("Range","bytes="+this._start+"-"+e));try{t.send(this._config.downloadRequestBody)}catch(e){this._chunkError(e.message)}n&&0===t.status&&this._chunkError()}},this._chunkLoaded=function(){let e;4===t.readyState&&(t.status<200||400<=t.status?this._chunkError():(this._start+=this._config.chunkSize||t.responseText.length,this._finished=!this._config.chunkSize||this._start>=(null!==(e=(e=t).getResponseHeader("Content-Range"))?parseInt(e.substring(e.lastIndexOf("/")+1)):-1),this.parseChunk(t.responseText)))},this._chunkError=function(e){e=t.statusText||e,this._sendError(Error(e))}}function c(e){(e=e||{}).chunkSize||(e.chunkSize=a.LocalChunkSize),u.call(this,e);var t,r,n="undefined"!=typeof FileReader;this.stream=function(e){this._input=e,r=e.slice||e.webkitSlice||e.mozSlice,n?((t=new FileReader).onload=_(this._chunkLoaded,this),t.onerror=_(this._chunkError,this)):t=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(e.target.result)},this._chunkError=function(){this._sendError(t.error)}}function f(e){var t;u.call(this,e=e||{}),this.stream=function(e){return t=e,this._nextChunk()},this._nextChunk=function(){var e,r;if(!this._finished)return t=(e=this._config.chunkSize)?(r=t.substring(0,e),t.substring(e)):(r=t,""),this._finished=!t,this.parseChunk(r)}}function d(e){u.call(this,e=e||{});var t=[],r=!0,n=!1;this.pause=function(){u.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){u.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(e){this._input=e,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){n&&1===t.length&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),t.length?this.parseChunk(t.shift()):r=!0},this._streamData=_(function(e){try{t.push("string"==typeof e?e:e.toString(this._config.encoding)),r&&(r=!1,this._checkIsFinished(),this.parseChunk(t.shift()))}catch(e){this._streamError(e)}},this),this._streamError=_(function(e){this._streamCleanUp(),this._sendError(e)},this),this._streamEnd=_(function(){this._streamCleanUp(),n=!0,this._streamData("")},this),this._streamCleanUp=_(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function h(e){var t,r,n,i,o=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,s=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,u=this,l=0,c=0,f=!1,d=!1,h=[],g={data:[],errors:[],meta:{}};function v(t){return"greedy"===e.skipEmptyLines?""===t.join("").trim():1===t.length&&0===t[0].length}function y(){if(g&&n&&(k("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),n=!1),e.skipEmptyLines&&(g.data=g.data.filter(function(e){return!v(e)})),_()){if(g){if(Array.isArray(g.data[0])){for(var t,r=0;_()&&r=h.length?"__parsed_extra":h[i]:a,l=u=e.transform?e.transform(u,a):u,(e.dynamicTypingFunction&&void 0===e.dynamicTyping[r]&&(e.dynamicTyping[r]=e.dynamicTypingFunction(r)),!0===(e.dynamicTyping[r]||e.dynamicTyping))?"true"===l||"TRUE"===l||"false"!==l&&"FALSE"!==l&&((e=>{if(o.test(e)&&-9007199254740992<(e=parseFloat(e))&&e<9007199254740992)return 1})(l)?parseFloat(l):s.test(l)?new Date(l):""===l?null:l):l);"__parsed_extra"===a?(n[a]=n[a]||[],n[a].push(u)):n[a]=u}return e.header&&(i>h.length?k("FieldMismatch","TooManyFields","Too many fields: expected "+h.length+" fields but parsed "+i,c+r):ie.preview?r.abort():(g.data=g.data[0],i(g,u))))}),this.parse=function(i,o,s){var u=e.quoteChar||'"',u=(e.newline||(e.newline=this.guessLineEndings(i,u)),n=!1,e.delimiter?w(e.delimiter)&&(e.delimiter=e.delimiter(i),g.meta.delimiter=e.delimiter):((u=((t,r,n,i,o)=>{var s,u,l,c;o=o||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var f=0;f=r.length/2?"\r\n":"\r"}}function p(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function m(e){var t=(e=e||{}).delimiter,r=e.newline,n=e.comments,i=e.step,o=e.preview,s=e.fastMode,u=null,l=!1,c=null==e.quoteChar?'"':e.quoteChar,f=c;if(void 0!==e.escapeChar&&(f=e.escapeChar),("string"!=typeof t||-1=o)return N(!0);break}x.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:E.length,index:d}),D++}}else if(n&&0===C.length&&a.substring(d,d+_)===n){if(-1===T)return N();d=T+b,T=a.indexOf(r,d),j=a.indexOf(t,d)}else if(-1!==j&&(j=o)return N(!0)}return M();function P(e){E.push(e),O=d}function A(e){return -1!==e&&(e=a.substring(D+1,e))&&""===e.trim()?e.length:0}function M(e){return g||(void 0===e&&(e=a.substring(d)),C.push(e),d=v,P(C),k&&F()),N()}function z(e){d=e,P(C),C=[],T=a.indexOf(r,d)}function N(n){if(e.header&&!m&&E.length&&!l){var i=E[0],o=Object.create(null),s=new Set(i);let t=!1;for(let r=0;r{if("object"==typeof t){if("string"!=typeof t.delimiter||a.BAD_DELIMITERS.filter(function(e){return -1!==t.delimiter.indexOf(e)}).length||(i=t.delimiter),("boolean"==typeof t.quotes||"function"==typeof t.quotes||Array.isArray(t.quotes))&&(r=t.quotes),"boolean"!=typeof t.skipEmptyLines&&"string"!=typeof t.skipEmptyLines||(l=t.skipEmptyLines),"string"==typeof t.newline&&(o=t.newline),"string"==typeof t.quoteChar&&(s=t.quoteChar),"boolean"==typeof t.header&&(n=t.header),Array.isArray(t.columns)){if(0===t.columns.length)throw Error("Option columns is empty");c=t.columns}void 0!==t.escapeChar&&(u=t.escapeChar+s),t.escapeFormulae instanceof RegExp?f=t.escapeFormulae:"boolean"==typeof t.escapeFormulae&&t.escapeFormulae&&(f=/^[=+\-@\t\r].*$/)}})(),RegExp(p(s),"g"));if("string"==typeof e&&(e=JSON.parse(e)),Array.isArray(e)){if(!e.length||Array.isArray(e[0]))return h(null,e,l);if("object"==typeof e[0])return h(c||Object.keys(e[0]),e,l)}else if("object"==typeof e)return"string"==typeof e.data&&(e.data=JSON.parse(e.data)),Array.isArray(e.data)&&(e.fields||(e.fields=e.meta&&e.meta.fields||c),e.fields||(e.fields=Array.isArray(e.data[0])?e.fields:"object"==typeof e.data[0]?Object.keys(e.data[0]):[]),Array.isArray(e.data[0])||"object"==typeof e.data[0]||(e.data=[e.data])),h(e.fields||[],e.data||[],l);throw Error("Unable to serialize unrecognized input");function h(e,t,r){var s="",a=("string"==typeof e&&(e=JSON.parse(e)),"string"==typeof t&&(t=JSON.parse(t)),Array.isArray(e)&&0{for(var r=0;r=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}(e,s),n=i.default.Children.only(t);return i.default.cloneElement(n,l(l({},r),{},{onClick:this.onClick}))}}],function(e,t){for(var r=0;r({...e,disclosureState:(0,v.E)(e.disclosureState,{0:1,1:0})}),1:e=>1===e.disclosureState?e:{...e,disclosureState:1},2:(e,t)=>e.buttonId===t.buttonId?e:{...e,buttonId:t.buttonId},3:(e,t)=>e.panelId===t.panelId?e:{...e,panelId:t.panelId},4:(e,t)=>e.buttonElement===t.element?e:{...e,buttonElement:t.element},5:(e,t)=>e.panelElement===t.element?e:{...e,panelElement:t.element}},C=(0,u.createContext)(null);function O(e){let t=(0,u.useContext)(C);if(null===t){let t=Error("<".concat(e," /> is missing a parent component."));throw Error.captureStackTrace&&Error.captureStackTrace(t,O),t}return t}C.displayName="DisclosureContext";let S=(0,u.createContext)(null);S.displayName="DisclosureAPIContext";let R=(0,u.createContext)(null);function j(e,t){return(0,v.E)(t.type,x,e,t)}R.displayName="DisclosurePanelContext";let T=u.Fragment,I=b.VN.RenderStrategy|b.VN.Static,D=Object.assign((0,b.yV)(function(e,t){let{defaultOpen:r=!1,...n}=e,i=(0,u.useRef)(null),o=(0,d.T)(t,(0,d.h)(e=>{i.current=e},void 0===e.as||e.as===u.Fragment)),s=(0,u.useReducer)(j,{disclosureState:r?0:1,buttonElement:null,panelElement:null,buttonId:null,panelId:null}),[{disclosureState:a,buttonId:l},f]=s,h=(0,c.z)(e=>{f({type:1});let t=(0,y.r)(i);if(!t||!l)return;let r=e?e instanceof HTMLElement?e:e.current instanceof HTMLElement?e.current:t.getElementById(l):t.getElementById(l);null==r||r.focus()}),g=(0,u.useMemo)(()=>({close:h}),[h]),_=(0,u.useMemo)(()=>({open:0===a,close:h}),[a,h]),w=(0,b.L6)();return u.createElement(C.Provider,{value:s},u.createElement(S.Provider,{value:g},u.createElement(p.Z,{value:h},u.createElement(m.up,{value:(0,v.E)(a,{0:m.ZM.Open,1:m.ZM.Closed})},w({ourProps:{ref:o},theirProps:n,slot:_,defaultTag:T,name:"Disclosure"})))))}),{Button:(0,b.yV)(function(e,t){let r=(0,u.useId)(),{id:n="headlessui-disclosure-button-".concat(r),disabled:i=!1,autoFocus:o=!1,...h}=e,[p,m]=O("Disclosure.Button"),v=(0,u.useContext)(R),y=null!==v&&v===p.panelId,_=(0,u.useRef)(null),k=(0,d.T)(_,t,(0,c.z)(e=>{if(!y)return m({type:4,element:e})}));(0,u.useEffect)(()=>{if(!y)return m({type:2,buttonId:n}),()=>{m({type:2,buttonId:null})}},[n,m,y]);let E=(0,c.z)(e=>{var t;if(y){if(1===p.disclosureState)return;switch(e.key){case w.R.Space:case w.R.Enter:e.preventDefault(),e.stopPropagation(),m({type:0}),null==(t=p.buttonElement)||t.focus()}}else switch(e.key){case w.R.Space:case w.R.Enter:e.preventDefault(),e.stopPropagation(),m({type:0})}}),x=(0,c.z)(e=>{e.key===w.R.Space&&e.preventDefault()}),C=(0,c.z)(e=>{var t;(0,g.P)(e.currentTarget)||i||(y?(m({type:0}),null==(t=p.buttonElement)||t.focus()):m({type:0}))}),{isFocusVisible:S,focusProps:j}=(0,s.F)({autoFocus:o}),{isHovered:T,hoverProps:I}=(0,a.X)({isDisabled:i}),{pressed:D,pressProps:L}=(0,l.x)({disabled:i}),P=(0,u.useMemo)(()=>({open:0===p.disclosureState,hover:T,active:D,disabled:i,focus:S,autofocus:o}),[p,T,D,S,i,o]),A=(0,f.f)(e,p.buttonElement),M=y?(0,b.dG)({ref:k,type:A,disabled:i||void 0,autoFocus:o,onKeyDown:E,onClick:C},j,I,L):(0,b.dG)({ref:k,id:n,type:A,"aria-expanded":0===p.disclosureState,"aria-controls":p.panelElement?p.panelId:void 0,disabled:i||void 0,autoFocus:o,onKeyDown:E,onKeyUp:x,onClick:C},j,I,L);return(0,b.L6)()({ourProps:M,theirProps:h,slot:P,defaultTag:"button",name:"Disclosure.Button"})}),Panel:(0,b.yV)(function(e,t){let r=(0,u.useId)(),{id:n="headlessui-disclosure-panel-".concat(r),transition:i=!1,...o}=e,[s,a]=O("Disclosure.Panel"),{close:l}=function e(t){let r=(0,u.useContext)(S);if(null===r){let r=Error("<".concat(t," /> is missing a parent component."));throw Error.captureStackTrace&&Error.captureStackTrace(r,e),r}return r}("Disclosure.Panel"),[f,p]=(0,u.useState)(null),g=(0,d.T)(t,(0,c.z)(e=>{_(()=>a({type:5,element:e}))}),p);(0,u.useEffect)(()=>(a({type:3,panelId:n}),()=>{a({type:3,panelId:null})}),[n,a]);let v=(0,m.oJ)(),[y,w]=(0,h.Y)(i,f,null!==v?(v&m.ZM.Open)===m.ZM.Open:0===s.disclosureState),k=(0,u.useMemo)(()=>({open:0===s.disclosureState,close:l}),[s.disclosureState,l]),E={ref:g,id:n,...(0,h.X)(w)},x=(0,b.L6)();return u.createElement(m.uu,null,u.createElement(R.Provider,{value:s.panelId},x({ourProps:E,theirProps:o,slot:k,defaultTag:"div",features:I,visible:y,name:"Disclosure.Panel"})))})})},33443:function(e,t,r){"use strict";r.d(t,{Z:function(){return o}});var n=r(2265);let i=(0,n.createContext)(()=>{});function o(e){let{value:t,children:r}=e;return n.createElement(i.Provider,{value:t},r)}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1789-c534ff8966aa231a.js b/litellm/proxy/_experimental/out/_next/static/chunks/1789-c534ff8966aa231a.js deleted file mode 100644 index a555310c8a2..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/1789-c534ff8966aa231a.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1789],{25512:function(e,s,l){l.d(s,{P:function(){return t.Z},Q:function(){return i.Z}});var t=l(27281),i=l(57365)},51789:function(e,s,l){l.d(s,{Z:function(){return e1}});var t=l(57437),i=l(2265),r=l(57840),n=l(51653),a=l(99376),o=l(10032),c=l(4260),d=l(5545),u=l(22116);l(25512);var m=l(78489),g=l(94789),p=l(12514),x=l(12485),h=l(18135),_=l(35242),f=l(29706),j=l(77991),y=l(21626),v=l(97214),b=l(28241),S=l(58834),Z=l(69552),w=l(71876),N=l(37592),I=l(4156),C=l(56522),k=l(19250),O=l(9114),E=l(85968);let T={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:""},L={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-domain/authorize"},{label:"Token Endpoint",name:"generic_token_endpoint",placeholder:"https://your-domain/token"},{label:"Userinfo Endpoint",name:"generic_userinfo_endpoint",placeholder:"https://your-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 P=e=>{let{isAddSSOModalVisible:s,isInstructionsModalVisible:l,handleAddSSOOk:r,handleAddSSOCancel:n,handleShowInstructions:a,handleInstructionsOk:m,handleInstructionsCancel:g,form:p,accessToken:x,ssoConfigured:h=!1}=e,[_,f]=(0,i.useState)(!1);(0,i.useEffect)(()=>{(async()=>{if(s&&x)try{let s=await (0,k.getSSOSettings)(x);if(console.log("Raw SSO data received:",s),s&&s.values){var e,l,t,i,r,n;console.log("SSO values:",s.values),console.log("user_email from API:",s.values.user_email);let a=null;s.values.google_client_id?a="google":s.values.microsoft_client_id?a="microsoft":s.values.generic_client_id&&(a=(null===(e=s.values.generic_authorization_endpoint)||void 0===e?void 0:e.includes("okta"))||(null===(l=s.values.generic_authorization_endpoint)||void 0===l?void 0:l.includes("auth0"))?"okta":"generic");let o={};if(s.values.role_mappings){let e=s.values.role_mappings,l=e=>e&&0!==e.length?e.join(", "):"";o={use_role_mappings:!0,group_claim:e.group_claim,default_role:e.default_role||"internal_user",proxy_admin_teams:l(null===(t=e.roles)||void 0===t?void 0:t.proxy_admin),admin_viewer_teams:l(null===(i=e.roles)||void 0===i?void 0:i.proxy_admin_viewer),internal_user_teams:l(null===(r=e.roles)||void 0===r?void 0:r.internal_user),internal_viewer_teams:l(null===(n=e.roles)||void 0===n?void 0:n.internal_user_viewer)}}let c={sso_provider:a,proxy_base_url:s.values.proxy_base_url,user_email:s.values.user_email,...s.values,...o};console.log("Setting form values:",c),p.resetFields(),setTimeout(()=>{p.setFieldsValue(c),console.log("Form values set, current form values:",p.getFieldsValue())},100)}}catch(e){console.error("Failed to load SSO settings:",e)}})()},[s,x,p]);let j=async e=>{if(!x){O.Z.fromBackend("No access token available");return}try{let{proxy_admin_teams:s,admin_viewer_teams:l,internal_user_teams:t,internal_viewer_teams:i,default_role:r,group_claim:n,use_role_mappings:o,...c}=e,d={...c};if(o){let e=e=>e&&""!==e.trim()?e.split(",").map(e=>e.trim()).filter(e=>e.length>0):[];d.role_mappings={provider:"generic",group_claim:n,default_role:({internal_user_viewer:"internal_user_viewer",internal_user:"internal_user",proxy_admin_viewer:"proxy_admin_viewer",proxy_admin:"proxy_admin"})[r]||"internal_user",roles:{proxy_admin:e(s),proxy_admin_viewer:e(l),internal_user:e(t),internal_user_viewer:e(i)}}}await (0,k.updateSSOSettings)(x,d),a(e)}catch(e){O.Z.fromBackend("Failed to save SSO settings: "+(0,E.O)(e))}},y=async()=>{if(!x){O.Z.fromBackend("No access token available");return}try{await (0,k.updateSSOSettings)(x,{google_client_id:null,google_client_secret:null,microsoft_client_id:null,microsoft_client_secret:null,microsoft_tenant:null,generic_client_id:null,generic_client_secret:null,generic_authorization_endpoint:null,generic_token_endpoint:null,generic_userinfo_endpoint:null,proxy_base_url:null,user_email:null,sso_provider:null,role_mappings:null}),p.resetFields(),f(!1),r(),O.Z.success("SSO settings cleared successfully")}catch(e){console.error("Failed to clear SSO settings:",e),O.Z.fromBackend("Failed to clear SSO settings")}},v=e=>{let s=L[e];return s?s.fields.map(e=>(0,t.jsx)(o.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,t.jsx)(c.default.Password,{}):(0,t.jsx)(C.o,{placeholder:e.placeholder})},e.name)):null};return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(u.Z,{title:h?"Edit SSO Settings":"Add SSO",visible:s,width:800,footer:null,onOk:r,onCancel:n,children:(0,t.jsxs)(o.Z,{form:p,onFinish:j,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(o.Z.Item,{label:"SSO Provider",name:"sso_provider",rules:[{required:!0,message:"Please select an SSO provider"}],children:(0,t.jsx)(N.default,{children:Object.entries(T).map(e=>{let[s,l]=e;return(0,t.jsx)(N.default.Option,{value:s,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"4px 0"},children:[l&&(0,t.jsx)("img",{src:l,alt:s,style:{height:24,width:24,marginRight:12,objectFit:"contain"}}),(0,t.jsxs)("span",{children:["okta"===s.toLowerCase()?"Okta / Auth0":s.charAt(0).toUpperCase()+s.slice(1)," ","SSO"]})]})},s)})})}),(0,t.jsx)(o.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?v(l):null}}),(0,t.jsx)(o.Z.Item,{label:"Proxy Admin Email",name:"user_email",rules:[{required:!0,message:"Please enter the email of the proxy admin"}],children:(0,t.jsx)(C.o,{})}),(0,t.jsx)(o.Z.Item,{label:"Proxy Base URL",name:"proxy_base_url",normalize:e=>null==e?void 0:e.trim(),rules:[{required:!0,message:"Please enter the proxy base url"},{pattern:/^https?:\/\/.+/,message:"URL must start with http:// or https://"},{validator:(e,s)=>s&&/^https?:\/\/.+/.test(s)&&s.endsWith("/")?Promise.reject("URL must not end with a trailing slash"):Promise.resolve()}],children:(0,t.jsx)(C.o,{placeholder:"https://example.com"})}),(0,t.jsx)(o.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.sso_provider!==s.sso_provider,children:e=>{let{getFieldValue:s}=e,l=s("sso_provider");return"okta"===l||"generic"===l?(0,t.jsx)(o.Z.Item,{label:"Use Role Mappings",name:"use_role_mappings",valuePropName:"checked",children:(0,t.jsx)(I.Z,{})}):null}}),(0,t.jsx)(o.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.use_role_mappings!==s.use_role_mappings,children:e=>{let{getFieldValue:s}=e;return s("use_role_mappings")?(0,t.jsx)(o.Z.Item,{label:"Group Claim",name:"group_claim",rules:[{required:!0,message:"Please enter the group claim"}],children:(0,t.jsx)(C.o,{})}):null}}),(0,t.jsx)(o.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.use_role_mappings!==s.use_role_mappings,children:e=>{let{getFieldValue:s}=e;return s("use_role_mappings")?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(o.Z.Item,{label:"Default Role",name:"default_role",initialValue:"Internal User",children:(0,t.jsxs)(N.default,{children:[(0,t.jsx)(N.default.Option,{value:"internal_user_viewer",children:"Internal Viewer"}),(0,t.jsx)(N.default.Option,{value:"internal_user",children:"Internal User"}),(0,t.jsx)(N.default.Option,{value:"proxy_admin_viewer",children:"Admin Viewer"}),(0,t.jsx)(N.default.Option,{value:"proxy_admin",children:"Proxy Admin"})]})}),(0,t.jsx)(o.Z.Item,{label:"Proxy Admin Teams",name:"proxy_admin_teams",children:(0,t.jsx)(C.o,{})}),(0,t.jsx)(o.Z.Item,{label:"Admin Viewer Teams",name:"admin_viewer_teams",children:(0,t.jsx)(C.o,{})}),(0,t.jsx)(o.Z.Item,{label:"Internal User Teams",name:"internal_user_teams",children:(0,t.jsx)(C.o,{})}),(0,t.jsx)(o.Z.Item,{label:"Internal Viewer Teams",name:"internal_viewer_teams",children:(0,t.jsx)(C.o,{})})]}):null}})]}),(0,t.jsxs)("div",{style:{textAlign:"right",marginTop:"10px",display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"8px"},children:[h&&(0,t.jsx)(d.ZP,{onClick:()=>f(!0),style:{backgroundColor:"#6366f1",borderColor:"#6366f1",color:"white"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#5558eb",e.currentTarget.style.borderColor="#5558eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#6366f1",e.currentTarget.style.borderColor="#6366f1"},children:"Clear"}),(0,t.jsx)(d.ZP,{htmlType:"submit",children:"Save"})]})]})}),(0,t.jsxs)(u.Z,{title:"Confirm Clear SSO Settings",visible:_,onOk:y,onCancel:()=>f(!1),okText:"Yes, Clear",cancelText:"Cancel",okButtonProps:{danger:!0,style:{backgroundColor:"#dc2626",borderColor:"#dc2626"}},children:[(0,t.jsx)("p",{children:"Are you sure you want to clear all SSO settings? This action cannot be undone."}),(0,t.jsx)("p",{children:"Users will no longer be able to login using SSO after this change."})]}),(0,t.jsxs)(u.Z,{title:"SSO Setup Instructions",visible:l,width:800,footer:null,onOk:m,onCancel:g,children:[(0,t.jsx)("p",{children:"Follow these steps to complete the SSO setup:"}),(0,t.jsx)(C.x,{className:"mt-2",children:"1. DO NOT Exit this TAB"}),(0,t.jsx)(C.x,{className:"mt-2",children:"2. Open a new tab, visit your proxy base url"}),(0,t.jsx)(C.x,{className:"mt-2",children:"3. Confirm your SSO is configured correctly and you can login on the new Tab"}),(0,t.jsx)(C.x,{className:"mt-2",children:"4. If Step 3 is successful, you can close this tab"}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(d.ZP,{onClick:m,children:"Done"})})]})]})},A=l(67982),U=l(67101),R=l(84264),M=l(49566),z=l(96761),F=l(29233),G=l(62272),D=l(23639),B=l(92403),V=l(29271),q=l(34419),Y=e=>{let{accessToken:s,userID:l,proxySettings:r}=e,[n]=o.Z.useForm(),[a,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(null),[x,h]=(0,i.useState)("");(0,i.useEffect)(()=>{let e="";h(r&&r.PROXY_BASE_URL&&void 0!==r.PROXY_BASE_URL?r.PROXY_BASE_URL:window.location.origin)},[r]);let _="".concat(x,"/scim/v2"),f=async e=>{if(!s||!l){O.Z.fromBackend("You need to be logged in to create a SCIM token");return}try{c(!0);let t={key_alias:e.key_alias||"SCIM Access Token",team_id:null,models:[],allowed_routes:["/scim/*"]},i=await (0,k.keyCreateCall)(s,l,t);u(i),O.Z.success("SCIM token created successfully")}catch(e){console.error("Error creating SCIM token:",e),O.Z.fromBackend("Failed to create SCIM token: "+(0,E.O)(e))}finally{c(!1)}};return(0,t.jsx)(U.Z,{numItems:1,children:(0,t.jsxs)(p.Z,{children:[(0,t.jsx)("div",{className:"flex items-center mb-4",children:(0,t.jsx)(z.Z,{children:"SCIM Configuration"})}),(0,t.jsx)(R.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,t.jsx)(A.Z,{}),(0,t.jsxs)("div",{className:"space-y-8",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center mb-2",children:[(0,t.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,t.jsxs)(z.Z,{className:"text-lg flex items-center",children:[(0,t.jsx)(G.Z,{className:"h-5 w-5 mr-2"}),"SCIM Tenant URL"]})]}),(0,t.jsx)(R.Z,{className:"text-gray-600 mb-3",children:"Use this URL in your identity provider SCIM integration settings."}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(M.Z,{value:_,disabled:!0,className:"flex-grow"}),(0,t.jsx)(F.CopyToClipboard,{text:_,onCopy:()=>O.Z.success("URL copied to clipboard"),children:(0,t.jsxs)(m.Z,{variant:"primary",className:"ml-2 flex items-center",children:[(0,t.jsx)(D.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center mb-2",children:[(0,t.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,t.jsxs)(z.Z,{className:"text-lg flex items-center",children:[(0,t.jsx)(B.Z,{className:"h-5 w-5 mr-2"}),"Authentication Token"]})]}),(0,t.jsx)(g.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."}),d?(0,t.jsxs)(p.Z,{className:"border border-yellow-300 bg-yellow-50",children:[(0,t.jsxs)("div",{className:"flex items-center mb-2 text-yellow-800",children:[(0,t.jsx)(V.Z,{className:"h-5 w-5 mr-2"}),(0,t.jsx)(z.Z,{className:"text-lg text-yellow-800",children:"Your SCIM Token"})]}),(0,t.jsx)(R.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,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(M.Z,{value:d.key,className:"flex-grow mr-2 bg-white",type:"password",disabled:!0}),(0,t.jsx)(F.CopyToClipboard,{text:d.key,onCopy:()=>O.Z.success("Token copied to clipboard"),children:(0,t.jsxs)(m.Z,{variant:"primary",className:"flex items-center",children:[(0,t.jsx)(D.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]}),(0,t.jsxs)(m.Z,{className:"mt-4 flex items-center",variant:"secondary",onClick:()=>u(null),children:[(0,t.jsx)(q.Z,{className:"h-4 w-4 mr-1"}),"Create Another Token"]})]}):(0,t.jsx)("div",{className:"bg-gray-50 p-4 rounded-lg",children:(0,t.jsxs)(o.Z,{form:n,onFinish:f,layout:"vertical",children:[(0,t.jsx)(o.Z.Item,{name:"key_alias",label:"Token Name",rules:[{required:!0,message:"Please enter a name for your token"}],children:(0,t.jsx)(M.Z,{placeholder:"SCIM Access Token"})}),(0,t.jsx)(o.Z.Item,{children:(0,t.jsxs)(m.Z,{variant:"primary",type:"submit",loading:a,className:"flex items-center",children:[(0,t.jsx)(B.Z,{className:"h-4 w-4 mr-1"}),"Create SCIM Token"]})})]})})]})]})]})})},K=e=>{let{accessToken:s,onSuccess:l}=e,[r]=o.Z.useForm(),[n,a]=(0,i.useState)(!1);(0,i.useEffect)(()=>{(async()=>{if(s)try{let e=await (0,k.getSSOSettings)(s);if(e&&e.values){let s=e.values.ui_access_mode,l={};s&&"object"==typeof s?l={ui_access_mode_type:s.type,restricted_sso_group:s.restricted_sso_group,sso_group_jwt_field:s.sso_group_jwt_field}:"string"==typeof s&&(l={ui_access_mode_type:s,restricted_sso_group:e.values.restricted_sso_group,sso_group_jwt_field:e.values.team_ids_jwt_field||e.values.sso_group_jwt_field}),r.setFieldsValue(l)}}catch(e){console.error("Failed to load UI access settings:",e)}})()},[s,r]);let c=async e=>{if(!s){O.Z.fromBackend("No access token available");return}a(!0);try{let t;t="all_authenticated_users"===e.ui_access_mode_type?{ui_access_mode:"none"}:{ui_access_mode:{type:e.ui_access_mode_type,restricted_sso_group:e.restricted_sso_group,sso_group_jwt_field:e.sso_group_jwt_field}},await (0,k.updateSSOSettings)(s,t),l()}catch(e){console.error("Failed to save UI access settings:",e),O.Z.fromBackend("Failed to save UI access settings")}finally{a(!1)}};return(0,t.jsxs)("div",{style:{padding:"16px"},children:[(0,t.jsx)("div",{style:{marginBottom:"16px"},children:(0,t.jsx)(C.x,{style:{fontSize:"14px",color:"#6b7280"},children:"Configure who can access the UI interface and how group information is extracted from JWT tokens."})}),(0,t.jsxs)(o.Z,{form:r,onFinish:c,layout:"vertical",children:[(0,t.jsx)(o.Z.Item,{label:"UI Access Mode",name:"ui_access_mode_type",tooltip:"Controls who can access the UI interface",children:(0,t.jsxs)(N.default,{placeholder:"Select access mode",children:[(0,t.jsx)(N.default.Option,{value:"all_authenticated_users",children:"All Authenticated Users"}),(0,t.jsx)(N.default.Option,{value:"restricted_sso_group",children:"Restricted SSO Group"})]})}),(0,t.jsx)(o.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.ui_access_mode_type!==s.ui_access_mode_type,children:e=>{let{getFieldValue:s}=e;return"restricted_sso_group"===s("ui_access_mode_type")?(0,t.jsx)(o.Z.Item,{label:"Restricted SSO Group",name:"restricted_sso_group",rules:[{required:!0,message:"Please enter the restricted SSO group"}],children:(0,t.jsx)(C.o,{placeholder:"ui-access-group"})}):null}}),(0,t.jsx)(o.Z.Item,{label:"SSO Group JWT Field",name:"sso_group_jwt_field",tooltip:"JWT field name that contains team/group information. Use dot notation to access nested fields.",children:(0,t.jsx)(C.o,{placeholder:"groups"})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"16px"},children:(0,t.jsx)(d.ZP,{type:"primary",htmlType:"submit",loading:n,style:{backgroundColor:"#6366f1",borderColor:"#6366f1"},children:"Update UI Access Control"})})]})]})},H=l(12363),W=l(55584),Q=l(29827),J=l(21770),X=l(90246);let $=(0,X.n)("uiSettings"),ee=e=>{let s=(0,Q.NL)();return(0,J.D)({mutationFn:async s=>{if(!e)throw Error("Access token is required");return(0,k.updateUiSettings)(e,s)},onSuccess:()=>{s.invalidateQueries({queryKey:$.all})}})};var es=l(39760),el=l(1633);let et={"api-keys":"Manage virtual keys for API access and authentication","llm-playground":"Interactive playground for testing LLM requests",models:"Configure and manage LLM models and endpoints",agents:"Create and manage AI agents","mcp-servers":"Configure Model Context Protocol servers",guardrails:"Set up content moderation and safety guardrails",policies:"Define access control and usage policies","search-tools":"Configure RAG search and retrieval tools","vector-stores":"Manage vector databases for embeddings",new_usage:"View usage analytics and metrics",logs:"Access request and response logs",users:"Manage internal user accounts and permissions",teams:"Create and manage teams for access control",organizations:"Manage organizations and their members",budgets:"Set and monitor spending budgets",api_ref:"Browse API documentation and endpoints","model-hub-table":"Explore available AI models and providers","learning-resources":"Access tutorials and documentation",caching:"Configure response caching settings","transform-request":"Set up request transformation rules","cost-tracking":"Track and analyze API costs","ui-theme":"Customize dashboard appearance","tag-management":"Organize resources with tags",prompts:"Manage and version prompt templates","claude-code-plugins":"Configure Claude Code plugins",usage:"View legacy usage dashboard","router-settings":"Configure routing and load balancing settings","logging-and-alerts":"Set up logging and alert configurations","admin-panel":"Access admin panel and settings"};var ei=l(20347);let er=e=>!e||0===e.length||e.some(e=>ei.lo.includes(e)),en=()=>{let e=[];return el.j.forEach(s=>{s.items.forEach(l=>{if(l.page&&"tools"!==l.page&&"experimental"!==l.page&&"settings"!==l.page&&er(l.roles)){let t="string"==typeof l.label?l.label:l.key;e.push({page:l.page,label:t,group:s.groupLabel,description:et[l.page]||"No description available"})}if(l.children){let t="string"==typeof l.label?l.label:l.key;l.children.forEach(l=>{if(er(l.roles)){let i="string"==typeof l.label?l.label:l.key;e.push({page:l.page,label:i,group:"".concat(s.groupLabel," > ").concat(t),description:et[l.page]||"No description available"})}})}})}),e};var ea=l(58760),eo=l(3810),ec=l(44851);function ed(e){let{enabledPagesInternalUsers:s,enabledPagesPropertyDescription:l,isUpdating:n,onUpdate:a}=e,o=null!=s,c=(0,i.useMemo)(()=>en(),[]),u=(0,i.useMemo)(()=>{let e={};return c.forEach(s=>{e[s.group]||(e[s.group]=[]),e[s.group].push(s)}),e},[c]),[m,g]=(0,i.useState)(s||[]);return(0,i.useMemo)(()=>{s?g(s):g([])},[s]),(0,t.jsxs)(ea.Z,{direction:"vertical",size:"middle",style:{width:"100%"},children:[(0,t.jsxs)(ea.Z,{direction:"vertical",size:4,children:[(0,t.jsxs)(ea.Z,{align:"center",children:[(0,t.jsx)(r.default.Text,{strong:!0,children:"Internal User Page Visibility"}),!o&&(0,t.jsx)(eo.Z,{color:"default",style:{marginLeft:"8px"},children:"Not set (all pages visible)"}),o&&(0,t.jsxs)(eo.Z,{color:"blue",style:{marginLeft:"8px"},children:[m.length," page",1!==m.length?"s":""," selected"]})]}),l&&(0,t.jsx)(r.default.Text,{type:"secondary",children:l}),(0,t.jsx)(r.default.Text,{type:"secondary",style:{fontSize:"12px",fontStyle:"italic"},children:"By default, all pages are visible to internal users. Select specific pages to restrict visibility."}),(0,t.jsx)(r.default.Text,{type:"secondary",style:{fontSize:"12px",color:"#8b5cf6"},children:"Note: Only pages accessible to internal user roles are shown here. Admin-only pages are excluded as they cannot be made visible to internal users regardless of this setting."})]}),(0,t.jsx)(ec.default,{items:[{key:"page-visibility",label:"Configure Page Visibility",children:(0,t.jsxs)(ea.Z,{direction:"vertical",size:"middle",style:{width:"100%"},children:[(0,t.jsx)(I.Z.Group,{value:m,onChange:g,style:{width:"100%"},children:(0,t.jsx)(ea.Z,{direction:"vertical",size:"middle",style:{width:"100%"},children:Object.entries(u).map(e=>{let[s,l]=e;return(0,t.jsxs)("div",{children:[(0,t.jsx)(r.default.Text,{strong:!0,style:{fontSize:"11px",color:"#6b7280",letterSpacing:"0.05em",display:"block",marginBottom:"8px"},children:s}),(0,t.jsx)(ea.Z,{direction:"vertical",size:"small",style:{marginLeft:"16px",width:"100%"},children:l.map(e=>(0,t.jsx)("div",{style:{marginBottom:"4px"},children:(0,t.jsx)(I.Z,{value:e.page,children:(0,t.jsxs)(ea.Z,{direction:"vertical",size:0,children:[(0,t.jsx)(r.default.Text,{children:e.label}),(0,t.jsx)(r.default.Text,{type:"secondary",style:{fontSize:"12px"},children:e.description})]})})},e.page))})]},s)})})}),(0,t.jsxs)(ea.Z,{children:[(0,t.jsx)(d.ZP,{type:"primary",onClick:()=>{a({enabled_ui_pages_internal_users:m.length>0?m:null})},loading:n,disabled:n,children:"Save Page Visibility Settings"}),o&&(0,t.jsx)(d.ZP,{onClick:()=>{g([]),a({enabled_ui_pages_internal_users:null})},loading:n,disabled:n,children:"Reset to Default (All Pages)"})]})]})}]})]})}var eu=l(5945),em=l(50337),eg=l(63709),ep=l(23496);function ex(){var e,s,l,i,a,o;let{accessToken:c}=(0,es.Z)(),{data:d,isLoading:u,isError:m,error:g}=(0,W.L)(),{mutate:p,isPending:x,error:h}=ee(c),_=null==d?void 0:d.field_schema,f=null==_?void 0:null===(e=_.properties)||void 0===e?void 0:e.disable_model_add_for_internal_users,j=null==_?void 0:null===(s=_.properties)||void 0===s?void 0:s.disable_team_admin_delete_team_user,y=null==_?void 0:null===(l=_.properties)||void 0===l?void 0:l.enabled_ui_pages_internal_users,v=null!==(i=null==d?void 0:d.values)&&void 0!==i?i:{},b=!!v.disable_model_add_for_internal_users,S=!!v.disable_team_admin_delete_team_user;return(0,t.jsx)(eu.Z,{title:"UI Settings",children:u?(0,t.jsx)(em.Z,{active:!0}):m?(0,t.jsx)(n.Z,{type:"error",message:"Could not load UI settings",description:g instanceof Error?g.message:void 0}):(0,t.jsxs)(ea.Z,{direction:"vertical",size:"large",style:{width:"100%"},children:[(null==_?void 0:_.description)&&(0,t.jsx)(r.default.Paragraph,{style:{marginBottom:0},children:_.description}),h&&(0,t.jsx)(n.Z,{type:"error",message:"Could not update UI settings",description:h instanceof Error?h.message:void 0}),(0,t.jsxs)(ea.Z,{align:"start",size:"middle",children:[(0,t.jsx)(eg.Z,{checked:b,disabled:x,loading:x,onChange:e=>{p({disable_model_add_for_internal_users:e},{onSuccess:()=>{O.Z.success("UI settings updated successfully")},onError:e=>{O.Z.fromBackend(e)}})},"aria-label":null!==(a=null==f?void 0:f.description)&&void 0!==a?a:"Disable model add for internal users"}),(0,t.jsxs)(ea.Z,{direction:"vertical",size:4,children:[(0,t.jsx)(r.default.Text,{strong:!0,children:"Disable model add for internal users"}),(null==f?void 0:f.description)&&(0,t.jsx)(r.default.Text,{type:"secondary",children:f.description})]})]}),(0,t.jsxs)(ea.Z,{align:"start",size:"middle",children:[(0,t.jsx)(eg.Z,{checked:S,disabled:x,loading:x,onChange:e=>{p({disable_team_admin_delete_team_user:e},{onSuccess:()=>{O.Z.success("UI settings updated successfully")},onError:e=>{O.Z.fromBackend(e)}})},"aria-label":null!==(o=null==j?void 0:j.description)&&void 0!==o?o:"Disable team admin delete team user"}),(0,t.jsxs)(ea.Z,{direction:"vertical",size:4,children:[(0,t.jsx)(r.default.Text,{strong:!0,children:"Disable team admin delete team user"}),(null==j?void 0:j.description)&&(0,t.jsx)(r.default.Text,{type:"secondary",children:j.description})]})]}),(0,t.jsx)(ep.Z,{}),(0,t.jsx)(ed,{enabledPagesInternalUsers:v.enabled_ui_pages_internal_users,enabledPagesPropertyDescription:null==y?void 0:y.description,isUpdating:x,onUpdate:e=>{p(e,{onSuccess:()=>{O.Z.success("Page visibility settings updated successfully")},onError:e=>{O.Z.fromBackend(e)}})}})]})})}var eh=l(11713);let e_=(0,X.n)("sso"),ef=()=>{let{accessToken:e,userId:s,userRole:l}=(0,es.Z)();return(0,eh.a)({queryKey:e_.detail("settings"),queryFn:async()=>await (0,k.getSSOSettings)(e),enabled:!!(e&&s&&l)})};var ej=l(76188),ey=l(88906),ev=l(15868),eb=l(18930);let eS={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:""},eZ={google:"Google SSO",microsoft:"Microsoft SSO",okta:"Okta / Auth0 SSO",generic:"Generic SSO"},ew={internal_user_viewer:"Internal Viewer",internal_user:"Internal User",proxy_admin_viewer:"Proxy Admin Viewer",proxy_admin:"Proxy Admin"};var eN=l(31283);let eI={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-domain/authorize"},{label:"Token Endpoint",name:"generic_token_endpoint",placeholder:"https://your-domain/token"},{label:"Userinfo Endpoint",name:"generic_userinfo_endpoint",placeholder:"https://your-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"}]}},eC=e=>{let s=eI[e];return s?s.fields.map(e=>(0,t.jsx)(o.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,t.jsx)(c.default.Password,{}):(0,t.jsx)(eN.o,{placeholder:e.placeholder})},e.name)):null};var ek=e=>{let{form:s,onFormSubmit:l}=e;return(0,t.jsx)("div",{children:(0,t.jsxs)(o.Z,{form:s,onFinish:l,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsx)(o.Z.Item,{label:"SSO Provider",name:"sso_provider",rules:[{required:!0,message:"Please select an SSO provider"}],children:(0,t.jsx)(N.default,{children:Object.entries(eS).map(e=>{let[s,l]=e;return(0,t.jsx)(N.default.Option,{value:s,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"4px 0"},children:[l&&(0,t.jsx)("img",{src:l,alt:s,style:{height:24,width:24,marginRight:12,objectFit:"contain"}}),(0,t.jsx)("span",{children:eZ[s]||s.charAt(0).toUpperCase()+s.slice(1)+" SSO"})]})},s)})})}),(0,t.jsx)(o.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?eC(l):null}}),(0,t.jsx)(o.Z.Item,{label:"Proxy Admin Email",name:"user_email",rules:[{required:!0,message:"Please enter the email of the proxy admin"}],children:(0,t.jsx)(eN.o,{})}),(0,t.jsx)(o.Z.Item,{label:"Proxy Base URL",name:"proxy_base_url",normalize:e=>null==e?void 0:e.trim(),rules:[{required:!0,message:"Please enter the proxy base url"},{pattern:/^https?:\/\/.+/,message:"URL must start with http:// or https://"},{validator:(e,s)=>s&&/^https?:\/\/.+/.test(s)&&s.endsWith("/")?Promise.reject("URL must not end with a trailing slash"):Promise.resolve()}],children:(0,t.jsx)(eN.o,{placeholder:"https://example.com"})}),(0,t.jsx)(o.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.sso_provider!==s.sso_provider,children:e=>{let{getFieldValue:s}=e,l=s("sso_provider");return"okta"===l||"generic"===l?(0,t.jsx)(o.Z.Item,{label:"Use Role Mappings",name:"use_role_mappings",valuePropName:"checked",children:(0,t.jsx)(I.Z,{})}):null}}),(0,t.jsx)(o.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.use_role_mappings!==s.use_role_mappings||e.sso_provider!==s.sso_provider,children:e=>{let{getFieldValue:s}=e,l=s("use_role_mappings"),i=s("sso_provider");return l&&("okta"===i||"generic"===i)?(0,t.jsx)(o.Z.Item,{label:"Group Claim",name:"group_claim",rules:[{required:!0,message:"Please enter the group claim"}],children:(0,t.jsx)(eN.o,{})}):null}}),(0,t.jsx)(o.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.use_role_mappings!==s.use_role_mappings||e.sso_provider!==s.sso_provider,children:e=>{let{getFieldValue:s}=e,l=s("use_role_mappings"),i=s("sso_provider");return l&&("okta"===i||"generic"===i)?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(o.Z.Item,{label:"Default Role",name:"default_role",initialValue:"Internal User",children:(0,t.jsxs)(N.default,{children:[(0,t.jsx)(N.default.Option,{value:"internal_user_viewer",children:"Internal Viewer"}),(0,t.jsx)(N.default.Option,{value:"internal_user",children:"Internal User"}),(0,t.jsx)(N.default.Option,{value:"proxy_admin_viewer",children:"Admin Viewer"}),(0,t.jsx)(N.default.Option,{value:"proxy_admin",children:"Proxy Admin"})]})}),(0,t.jsx)(o.Z.Item,{label:"Proxy Admin Teams",name:"proxy_admin_teams",children:(0,t.jsx)(eN.o,{})}),(0,t.jsx)(o.Z.Item,{label:"Admin Viewer Teams",name:"admin_viewer_teams",children:(0,t.jsx)(eN.o,{})}),(0,t.jsx)(o.Z.Item,{label:"Internal User Teams",name:"internal_user_teams",children:(0,t.jsx)(eN.o,{})}),(0,t.jsx)(o.Z.Item,{label:"Internal Viewer Teams",name:"internal_viewer_teams",children:(0,t.jsx)(eN.o,{})})]}):null}})]})})};let eO=()=>{let{accessToken:e}=(0,es.Z)();return(0,J.D)({mutationFn:async s=>{if(!e)throw Error("Access token is required");return await (0,k.updateSSOSettings)(e,s)}})},eE=e=>{let{proxy_admin_teams:s,admin_viewer_teams:l,internal_user_teams:t,internal_viewer_teams:i,default_role:r,group_claim:n,use_role_mappings:a,...o}=e,c={...o};if(a){let e=e=>e&&""!==e.trim()?e.split(",").map(e=>e.trim()).filter(e=>e.length>0):[];c.role_mappings={provider:"generic",group_claim:n,default_role:({internal_user_viewer:"internal_user_viewer",internal_user:"internal_user",proxy_admin_viewer:"proxy_admin_viewer",proxy_admin:"proxy_admin"})[r]||"internal_user",roles:{proxy_admin:e(s),proxy_admin_viewer:e(l),internal_user:e(t),internal_user_viewer:e(i)}}}return c},eT=e=>{if(e.google_client_id)return"google";if(e.microsoft_client_id)return"microsoft";if(e.generic_client_id){var s,l;return(null===(s=e.generic_authorization_endpoint)||void 0===s?void 0:s.includes("okta"))||(null===(l=e.generic_authorization_endpoint)||void 0===l?void 0:l.includes("auth0"))?"okta":"generic"}return null};var eL=e=>{let{isVisible:s,onCancel:l,onSuccess:i}=e,[r]=o.Z.useForm(),{mutateAsync:n,isPending:a}=eO(),c=async e=>{let s=eE(e);await n(s,{onSuccess:()=>{O.Z.success("SSO settings added successfully"),i()},onError:e=>{O.Z.fromBackend("Failed to save SSO settings: "+(0,E.O)(e))}})},m=()=>{r.resetFields(),l()};return(0,t.jsx)(u.Z,{title:"Add SSO",open:s,width:800,footer:(0,t.jsxs)(ea.Z,{children:[(0,t.jsx)(d.ZP,{onClick:m,disabled:a,children:"Cancel"}),(0,t.jsx)(d.ZP,{loading:a,onClick:()=>r.submit(),children:a?"Adding...":"Add SSO"})]}),onCancel:m,children:(0,t.jsx)(ek,{form:r,onFormSubmit:c})})},eP=l(21609),eA=e=>{let{isVisible:s,onCancel:l,onSuccess:i}=e,{data:r}=ef(),{mutateAsync:n,isPending:a}=eO(),o=async()=>{await n({google_client_id:null,google_client_secret:null,microsoft_client_id:null,microsoft_client_secret:null,microsoft_tenant:null,generic_client_id:null,generic_client_secret:null,generic_authorization_endpoint:null,generic_token_endpoint:null,generic_userinfo_endpoint:null,proxy_base_url:null,user_email:null,sso_provider:null,role_mappings:null},{onSuccess:()=>{O.Z.success("SSO settings cleared successfully"),l(),i()},onError:e=>{O.Z.fromBackend("Failed to clear SSO settings: "+(0,E.O)(e))}})};return(0,t.jsx)(eP.Z,{isOpen:s,title:"Confirm Clear SSO Settings",alertMessage:"This action cannot be undone.",message:"Are you sure you want to clear all SSO settings? Users will no longer be able to login using SSO after this change.",resourceInformationTitle:"SSO Settings",resourceInformation:[{label:"Provider",value:(null==r?void 0:r.values)&&eT(null==r?void 0:r.values)||"Generic"}],onCancel:l,onOk:o,confirmLoading:a})},eU=e=>{let{isVisible:s,onCancel:l,onSuccess:r}=e,[n]=o.Z.useForm(),a=ef(),{mutateAsync:c,isPending:m}=eO();(0,i.useEffect)(()=>{if(s&&a.data&&a.data.values){var e,l,t,i,r,o;let s=a.data;console.log("Raw SSO data received:",s),console.log("SSO values:",s.values),console.log("user_email from API:",s.values.user_email);let c=null;s.values.google_client_id?c="google":s.values.microsoft_client_id?c="microsoft":s.values.generic_client_id&&(c=(null===(e=s.values.generic_authorization_endpoint)||void 0===e?void 0:e.includes("okta"))||(null===(l=s.values.generic_authorization_endpoint)||void 0===l?void 0:l.includes("auth0"))?"okta":"generic");let d={};if(s.values.role_mappings){let e=s.values.role_mappings,l=e=>e&&0!==e.length?e.join(", "):"";d={use_role_mappings:!0,group_claim:e.group_claim,default_role:e.default_role||"internal_user",proxy_admin_teams:l(null===(t=e.roles)||void 0===t?void 0:t.proxy_admin),admin_viewer_teams:l(null===(i=e.roles)||void 0===i?void 0:i.proxy_admin_viewer),internal_user_teams:l(null===(r=e.roles)||void 0===r?void 0:r.internal_user),internal_viewer_teams:l(null===(o=e.roles)||void 0===o?void 0:o.internal_user_viewer)}}let u={sso_provider:c,...s.values,...d};console.log("Setting form values:",u),n.resetFields(),setTimeout(()=>{n.setFieldsValue(u),console.log("Form values set, current form values:",n.getFieldsValue())},100)}},[s,a.data,n]);let g=async e=>{try{let s=eE(e);await c(s,{onSuccess:()=>{O.Z.success("SSO settings updated successfully"),r()},onError:e=>{O.Z.fromBackend("Failed to save SSO settings: "+(0,E.O)(e))}})}catch(e){O.Z.fromBackend("Failed to process SSO settings: "+(0,E.O)(e))}},p=()=>{n.resetFields(),l()};return(0,t.jsx)(u.Z,{title:"Edit SSO Settings",open:s,width:800,footer:(0,t.jsxs)(ea.Z,{children:[(0,t.jsx)(d.ZP,{onClick:p,disabled:m,children:"Cancel"}),(0,t.jsx)(d.ZP,{loading:m,onClick:()=>n.submit(),children:m?"Saving...":"Save"})]}),onCancel:p,children:(0,t.jsx)(ek,{form:n,onFormSubmit:g})})},eR=l(42208),eM=l(87769);function ez(e){let{defaultHidden:s=!0,value:l}=e,[r,n]=(0,i.useState)(s);return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"font-mono text-gray-600 flex-1",children:l?r?"•".repeat(l.length):l:(0,t.jsx)("span",{className:"text-gray-400 italic",children:"Not configured"})}),l&&(0,t.jsx)(d.ZP,{type:"text",size:"small",icon:r?(0,t.jsx)(eR.Z,{className:"w-4 h-4"}):(0,t.jsx)(eM.Z,{className:"w-4 h-4"}),onClick:()=>n(!r),className:"text-gray-400 hover:text-gray-600"})]})}var eF=l(56609),eG=l(95805);let{Title:eD,Text:eB}=r.default;function eV(e){let{roleMappings:s}=e;if(!s)return null;let l=[{title:"Role",dataIndex:"role",key:"role",render:e=>(0,t.jsx)(eB,{strong:!0,children:ew[e]})},{title:"Mapped Groups",dataIndex:"groups",key:"groups",render:e=>(0,t.jsx)(t.Fragment,{children:e.length>0?e.map((e,s)=>(0,t.jsx)(eo.Z,{color:"blue",children:e},s)):(0,t.jsx)(eB,{className:"text-gray-400 italic",children:"No groups mapped"})})}];return(0,t.jsxs)(eu.Z,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(eG.Z,{className:"w-6 h-6 text-gray-400 mb-2"}),(0,t.jsx)(eD,{level:3,children:"Role Mappings"})]}),(0,t.jsxs)("div",{className:"space-y-8",children:[(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(eD,{level:5,children:"Group Claim"}),(0,t.jsx)("div",{children:(0,t.jsx)(eB,{code:!0,children:s.group_claim})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eD,{level:5,children:"Default Role"}),(0,t.jsx)("div",{children:(0,t.jsx)(eB,{strong:!0,children:ew[s.default_role]})})]})]}),(0,t.jsx)(ep.Z,{}),(0,t.jsx)(eF.Z,{columns:l,dataSource:Object.entries(s.roles).map(e=>{let[s,l]=e;return{role:s,groups:l}}),pagination:!1,bordered:!0,size:"small",className:"w-full"})]})]})}var eq=l(85180);let{Title:eY,Paragraph:eK}=r.default;function eH(e){let{onAdd:s}=e;return(0,t.jsx)("div",{className:"bg-white p-12 rounded-lg border border-dashed border-gray-300 text-center w-full",children:(0,t.jsx)(eq.Z,{image:eq.Z.PRESENTED_IMAGE_SIMPLE,description:(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(eY,{level:4,children:"No SSO Configuration Found"}),(0,t.jsx)(eK,{type:"secondary",className:"max-w-md mx-auto",children:"Configure Single Sign-On (SSO) to enable seamless authentication for your team members using your identity provider."})]}),children:(0,t.jsx)(d.ZP,{type:"primary",size:"large",onClick:s,className:"flex items-center gap-2 mx-auto mt-4",children:"Configure SSO"})})})}let{Title:eW,Text:eQ}=r.default;function eJ(){return(0,t.jsx)(eu.Z,{children:(0,t.jsxs)(ea.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(ey.Z,{className:"w-6 h-6 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eW,{level:3,children:"SSO Configuration"}),(0,t.jsx)(eQ,{type:"secondary",children:"Manage Single Sign-On authentication settings"})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(em.Z.Button,{active:!0,size:"default",style:{width:170,height:32}}),(0,t.jsx)(em.Z.Button,{active:!0,size:"default",style:{width:190,height:32}})]})]}),(0,t.jsxs)(ej.Z,{bordered:!0,column:{xxl:1,xl:1,lg:1,md:1,sm:1,xs:1},children:[(0,t.jsx)(ej.Z.Item,{label:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:100,height:16}})})}),(0,t.jsx)(ej.Z.Item,{label:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:200,height:16}})}),(0,t.jsx)(ej.Z.Item,{label:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:250,height:16}})}),(0,t.jsx)(ej.Z.Item,{label:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:180,height:16}})}),(0,t.jsx)(ej.Z.Item,{label:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)(em.Z.Node,{active:!0,style:{width:220,height:16}})})]})]})})}let{Title:eX,Text:e$}=r.default;function e0(){let{data:e,refetch:s,isLoading:l}=ef(),[r,n]=(0,i.useState)(!1),[a,o]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),m=!!(null==e?void 0:e.values.google_client_id)||!!(null==e?void 0:e.values.microsoft_client_id)||!!(null==e?void 0:e.values.generic_client_id),g=(null==e?void 0:e.values)?eT(e.values):null,p=!!(null==e?void 0:e.values.role_mappings),x=e=>(0,t.jsx)(e$,{className:"font-mono text-gray-600 text-sm",copyable:!!e,children:e||"-"}),h=e=>e||(0,t.jsx)("span",{className:"text-gray-400 italic",children:"Not configured"}),_={column:{xxl:1,xl:1,lg:1,md:1,sm:1,xs:1}},f={google:{providerText:eZ.google,fields:[{label:"Client ID",render:e=>(0,t.jsx)(ez,{value:e.google_client_id})},{label:"Client Secret",render:e=>(0,t.jsx)(ez,{value:e.google_client_secret})},{label:"Proxy Base URL",render:e=>h(e.proxy_base_url)}]},microsoft:{providerText:eZ.microsoft,fields:[{label:"Client ID",render:e=>(0,t.jsx)(ez,{value:e.microsoft_client_id})},{label:"Client Secret",render:e=>(0,t.jsx)(ez,{value:e.microsoft_client_secret})},{label:"Tenant",render:e=>h(e.microsoft_tenant)},{label:"Proxy Base URL",render:e=>h(e.proxy_base_url)}]},okta:{providerText:eZ.okta,fields:[{label:"Client ID",render:e=>(0,t.jsx)(ez,{value:e.generic_client_id})},{label:"Client Secret",render:e=>(0,t.jsx)(ez,{value:e.generic_client_secret})},{label:"Authorization Endpoint",render:e=>x(e.generic_authorization_endpoint)},{label:"Token Endpoint",render:e=>x(e.generic_token_endpoint)},{label:"User Info Endpoint",render:e=>x(e.generic_userinfo_endpoint)},{label:"Proxy Base URL",render:e=>h(e.proxy_base_url)}]},generic:{providerText:eZ.generic,fields:[{label:"Client ID",render:e=>(0,t.jsx)(ez,{value:e.generic_client_id})},{label:"Client Secret",render:e=>(0,t.jsx)(ez,{value:e.generic_client_secret})},{label:"Authorization Endpoint",render:e=>x(e.generic_authorization_endpoint)},{label:"Token Endpoint",render:e=>x(e.generic_token_endpoint)},{label:"User Info Endpoint",render:e=>x(e.generic_userinfo_endpoint)},{label:"Proxy Base URL",render:e=>h(e.proxy_base_url)}]}};return(0,t.jsxs)(t.Fragment,{children:[l?(0,t.jsx)(eJ,{}):(0,t.jsxs)(ea.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsx)(eu.Z,{children:(0,t.jsxs)(ea.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(ey.Z,{className:"w-6 h-6 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eX,{level:3,children:"SSO Configuration"}),(0,t.jsx)(e$,{type:"secondary",children:"Manage Single Sign-On authentication settings"})]})]}),(0,t.jsx)("div",{className:"flex items-center gap-3",children:m&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(d.ZP,{icon:(0,t.jsx)(ev.Z,{className:"w-4 h-4"}),onClick:()=>u(!0),children:"Edit SSO Settings"}),(0,t.jsx)(d.ZP,{danger:!0,icon:(0,t.jsx)(eb.Z,{className:"w-4 h-4"}),onClick:()=>n(!0),children:"Delete SSO Settings"})]})})]}),m?(()=>{if(!(null==e?void 0:e.values)||!g)return null;let{values:s}=e,l=f[g];return l?(0,t.jsxs)(ej.Z,{bordered:!0,..._,children:[(0,t.jsx)(ej.Z.Item,{label:"Provider",children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[eS[g]&&(0,t.jsx)("img",{src:eS[g],alt:g,style:{height:24,width:24,objectFit:"contain"}}),(0,t.jsx)("span",{children:l.providerText})]})}),l.fields.map((e,l)=>(0,t.jsx)(ej.Z.Item,{label:e.label,children:e.render(s)},l))]}):null})():(0,t.jsx)(eH,{onAdd:()=>o(!0)})]})}),p&&(0,t.jsx)(eV,{roleMappings:null==e?void 0:e.values.role_mappings})]}),(0,t.jsx)(eA,{isVisible:r,onCancel:()=>n(!1),onSuccess:()=>s()}),(0,t.jsx)(eL,{isVisible:a,onCancel:()=>o(!1),onSuccess:()=>{o(!1),s()}}),(0,t.jsx)(eU,{isVisible:c,onCancel:()=>u(!1),onSuccess:()=>{u(!1),s()}})]})}var e1=e=>{let{searchParams:s,accessToken:l,userID:N,showSSOBanner:I,premiumUser:C,proxySettings:E,userRole:T}=e,[L]=o.Z.useForm(),[A]=o.Z.useForm(),{Title:U,Paragraph:R}=r.default,[M,z]=(0,i.useState)(""),[F,G]=(0,i.useState)(null),[D,B]=(0,i.useState)(null),[V,q]=(0,i.useState)(!1),[W,Q]=(0,i.useState)(!1),[J,X]=(0,i.useState)(!1),[$,ee]=(0,i.useState)(!1),[es,el]=(0,i.useState)(!1),[et,ei]=(0,i.useState)(!1),[er,en]=(0,i.useState)(!1),[ea,eo]=(0,i.useState)(!1),[ec,ed]=(0,i.useState)(!1),[eu,em]=(0,i.useState)(!1),[eg,ep]=(0,i.useState)([]),[eh,e_]=(0,i.useState)(null),[ef,ej]=(0,i.useState)(!1);(0,a.useRouter)();let[ey,ev]=(0,i.useState)(null);console.log=function(){};let eb=(0,H.n)(),eS="All IP Addresses Allowed",eZ=eb;eZ+="/fallback/login";let ew=async()=>{if(l)try{let e=await (0,k.getSSOSettings)(l);if(console.log("SSO data:",e),e&&e.values){let s=e.values.google_client_id&&e.values.google_client_secret,l=e.values.microsoft_client_id&&e.values.microsoft_client_secret,t=e.values.generic_client_id&&e.values.generic_client_secret;ej(s||l||t)}else ej(!1)}catch(e){console.error("Error checking SSO configuration:",e),ej(!1)}},eN=async()=>{try{if(!0!==C){O.Z.fromBackend("This feature is only available for premium users. Please upgrade your account.");return}if(l){let e=await (0,k.getAllowedIPs)(l);ep(e&&e.length>0?e:[eS])}else ep([eS])}catch(e){console.error("Error fetching allowed IPs:",e),O.Z.fromBackend("Failed to fetch allowed IPs ".concat(e)),ep([eS])}finally{!0===C&&en(!0)}},eI=async e=>{try{if(l){await (0,k.addAllowedIP)(l,e.ip);let s=await (0,k.getAllowedIPs)(l);ep(s),O.Z.success("IP address added successfully")}}catch(e){console.error("Error adding IP:",e),O.Z.fromBackend("Failed to add IP address ".concat(e))}finally{eo(!1)}},eC=async e=>{e_(e),ed(!0)},ek=async()=>{if(eh&&l)try{await (0,k.deleteAllowedIP)(l,eh);let e=await (0,k.getAllowedIPs)(l);ep(e.length>0?e:[eS]),O.Z.success("IP address deleted successfully")}catch(e){console.error("Error deleting IP:",e),O.Z.fromBackend("Failed to delete IP address ".concat(e))}finally{ed(!1),e_(null)}};(0,i.useEffect)(()=>{(async()=>{if(null!=l){let e=[],s=await (0,k.userGetAllUsersCall)(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 i=(await (0,k.userGetAllUsersCall)(l,"proxy_admin")).users;i.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy admins: ".concat(i)),console.log("combinedList: ".concat(e)),G(e),ev(await (0,k.getPossibleUserRoles)(l))}})()},[l]),(0,i.useEffect)(()=>{ew()},[l,C]);let eO=()=>{em(!1)};return console.log("admins: ".concat(null==F?void 0:F.length)),(0,t.jsxs)("div",{className:"w-full m-2 mt-2 p-8",children:[(0,t.jsx)(U,{level:4,children:"Admin Access "}),(0,t.jsx)(R,{children:"Go to 'Internal Users' page to add other admins."}),(0,t.jsxs)(h.Z,{children:[(0,t.jsxs)(_.Z,{children:[(0,t.jsx)(x.Z,{children:"SSO Settings"}),(0,t.jsx)(x.Z,{children:"Security Settings"}),(0,t.jsx)(x.Z,{children:"SCIM"}),(0,t.jsx)(x.Z,{children:"UI Settings"})]}),(0,t.jsxs)(j.Z,{children:[(0,t.jsx)(f.Z,{children:(0,t.jsx)(e0,{})}),(0,t.jsxs)(f.Z,{children:[(0,t.jsxs)(p.Z,{children:[(0,t.jsx)(U,{level:4,children:" ✨ Security Settings"}),(0,t.jsx)(n.Z,{message:"SSO Configuration Deprecated",description:"Editing SSO Settings on this page is deprecated and will be removed in a future version. Please use the SSO Settings tab for SSO configuration.",type:"warning",showIcon:!0}),(0,t.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",marginTop:"1rem",marginLeft:"0.5rem"},children:[(0,t.jsx)("div",{children:(0,t.jsx)(m.Z,{style:{width:"150px"},onClick:()=>el(!0),children:ef?"Edit SSO Settings":"Add SSO"})}),(0,t.jsx)("div",{children:(0,t.jsx)(m.Z,{style:{width:"150px"},onClick:eN,children:"Allowed IPs"})}),(0,t.jsx)("div",{children:(0,t.jsx)(m.Z,{style:{width:"150px"},onClick:()=>!0===C?em(!0):O.Z.fromBackend("Only premium users can configure UI access control"),children:"UI Access Control"})})]})]}),(0,t.jsxs)("div",{className:"flex justify-start mb-4",children:[(0,t.jsx)(P,{isAddSSOModalVisible:es,isInstructionsModalVisible:et,handleAddSSOOk:()=>{el(!1),L.resetFields(),l&&C&&ew()},handleAddSSOCancel:()=>{el(!1),L.resetFields()},handleShowInstructions:e=>{el(!1),ei(!0)},handleInstructionsOk:()=>{ei(!1),l&&C&&ew()},handleInstructionsCancel:()=>{ei(!1),l&&C&&ew()},form:L,accessToken:l,ssoConfigured:ef}),(0,t.jsx)(u.Z,{title:"Manage Allowed IP Addresses",width:800,visible:er,onCancel:()=>en(!1),footer:[(0,t.jsx)(m.Z,{className:"mx-1",onClick:()=>eo(!0),children:"Add IP Address"},"add"),(0,t.jsx)(m.Z,{onClick:()=>en(!1),children:"Close"},"close")],children:(0,t.jsxs)(y.Z,{children:[(0,t.jsx)(S.Z,{children:(0,t.jsxs)(w.Z,{children:[(0,t.jsx)(Z.Z,{children:"IP Address"}),(0,t.jsx)(Z.Z,{className:"text-right",children:"Action"})]})}),(0,t.jsx)(v.Z,{children:eg.map((e,s)=>(0,t.jsxs)(w.Z,{children:[(0,t.jsx)(b.Z,{children:e}),(0,t.jsx)(b.Z,{className:"text-right",children:e!==eS&&(0,t.jsx)(m.Z,{onClick:()=>eC(e),color:"red",size:"xs",children:"Delete"})})]},s))})]})}),(0,t.jsx)(u.Z,{title:"Add Allowed IP Address",visible:ea,onCancel:()=>eo(!1),footer:null,children:(0,t.jsxs)(o.Z,{onFinish:eI,children:[(0,t.jsx)(o.Z.Item,{name:"ip",rules:[{required:!0,message:"Please enter an IP address"}],children:(0,t.jsx)(c.default,{placeholder:"Enter IP address"})}),(0,t.jsx)(o.Z.Item,{children:(0,t.jsx)(d.ZP,{htmlType:"submit",children:"Add IP Address"})})]})}),(0,t.jsx)(u.Z,{title:"Confirm Delete",visible:ec,onCancel:()=>ed(!1),onOk:ek,footer:[(0,t.jsx)(m.Z,{className:"mx-1",onClick:()=>ek(),children:"Yes"},"delete"),(0,t.jsx)(m.Z,{onClick:()=>ed(!1),children:"Close"},"close")],children:(0,t.jsxs)("p",{children:["Are you sure you want to delete the IP address: ",eh,"?"]})}),(0,t.jsx)(u.Z,{title:"UI Access Control Settings",visible:eu,width:600,footer:null,onOk:eO,onCancel:()=>{em(!1)},children:(0,t.jsx)(K,{accessToken:l,onSuccess:()=>{eO(),O.Z.success("UI Access Control settings updated successfully")}})})]}),(0,t.jsxs)(g.Z,{title:"Login without SSO",color:"teal",children:["If you need to login without sso, you can access"," ",(0,t.jsxs)("a",{href:eZ,target:"_blank",children:[(0,t.jsx)("b",{children:eZ})," "]})]})]}),(0,t.jsx)(f.Z,{children:(0,t.jsx)(Y,{accessToken:l,userID:N,proxySettings:E})}),(0,t.jsx)(f.Z,{children:(0,t.jsx)(ex,{})})]})]})]})}},1633:function(e,s,l){l.d(s,{j:function(){return R}});var t=l(57437),i=l(39823),r=l(39760),n=l(92403),a=l(28595),o=l(68208),c=l(69993),d=l(58630),u=l(57400),m=l(93750),g=l(29436),p=l(44625),x=l(9775),h=l(48231),_=l(15883),f=l(41361),j=l(37527),y=l(99458),v=l(12660),b=l(88009),S=l(71916),Z=l(41169),w=l(38434),N=l(71891),I=l(55322),C=l(11429),k=l(13817),O=l(18310),E=l(60985),T=l(2265),L=l(20347),P=l(79262),A=l(91027);let{Sider:U}=k.default,R=[{groupLabel:"AI GATEWAY",items:[{key:"api-keys",page:"api-keys",label:"Virtual Keys",icon:(0,t.jsx)(n.Z,{})},{key:"llm-playground",page:"llm-playground",label:"Playground",icon:(0,t.jsx)(a.Z,{}),roles:L.LQ},{key:"models",page:"models",label:"Models + Endpoints",icon:(0,t.jsx)(o.Z,{}),roles:L.LQ},{key:"agents",page:"agents",label:"Agents",icon:(0,t.jsx)(c.Z,{}),roles:L.LQ},{key:"mcp-servers",page:"mcp-servers",label:"MCP Servers",icon:(0,t.jsx)(d.Z,{})},{key:"guardrails",page:"guardrails",label:"Guardrails",icon:(0,t.jsx)(u.Z,{}),roles:L.ZL},{key:"policies",page:"policies",label:(0,t.jsx)("span",{className:"flex items-center gap-4",children:"Policies"}),icon:(0,t.jsx)(m.Z,{}),roles:L.ZL},{key:"tools",page:"tools",label:"Tools",icon:(0,t.jsx)(d.Z,{}),children:[{key:"search-tools",page:"search-tools",label:"Search Tools",icon:(0,t.jsx)(g.Z,{})},{key:"vector-stores",page:"vector-stores",label:"Vector Stores",icon:(0,t.jsx)(p.Z,{})}]}]},{groupLabel:"OBSERVABILITY",items:[{key:"new_usage",page:"new_usage",icon:(0,t.jsx)(x.Z,{}),roles:[...L.ZL,...L.lo],label:"Usage"},{key:"logs",page:"logs",label:(0,t.jsxs)("span",{className:"flex items-center gap-4",children:["Logs ",(0,t.jsx)(A.Z,{})]}),icon:(0,t.jsx)(h.Z,{})}]},{groupLabel:"ACCESS CONTROL",items:[{key:"users",page:"users",label:"Internal Users",icon:(0,t.jsx)(_.Z,{}),roles:L.ZL},{key:"teams",page:"teams",label:"Teams",icon:(0,t.jsx)(f.Z,{})},{key:"organizations",page:"organizations",label:"Organizations",icon:(0,t.jsx)(j.Z,{}),roles:L.ZL},{key:"budgets",page:"budgets",label:"Budgets",icon:(0,t.jsx)(y.Z,{}),roles:L.ZL}]},{groupLabel:"DEVELOPER TOOLS",items:[{key:"api_ref",page:"api_ref",label:"API Reference",icon:(0,t.jsx)(v.Z,{})},{key:"model-hub-table",page:"model-hub-table",label:"AI Hub",icon:(0,t.jsx)(b.Z,{})},{key:"learning-resources",page:"learning-resources",label:"Learning Resources",icon:(0,t.jsx)(S.Z,{}),external_url:"https://models.litellm.ai/cookbook"},{key:"experimental",page:"experimental",label:"Experimental",icon:(0,t.jsx)(Z.Z,{}),children:[{key:"caching",page:"caching",label:"Caching",icon:(0,t.jsx)(p.Z,{}),roles:L.ZL},{key:"prompts",page:"prompts",label:"Prompts",icon:(0,t.jsx)(w.Z,{}),roles:L.ZL},{key:"transform-request",page:"transform-request",label:"API Playground",icon:(0,t.jsx)(v.Z,{}),roles:[...L.ZL,...L.lo]},{key:"tag-management",page:"tag-management",label:"Tag Management",icon:(0,t.jsx)(N.Z,{}),roles:L.ZL},{key:"claude-code-plugins",page:"claude-code-plugins",label:"Claude Code Plugins",icon:(0,t.jsx)(d.Z,{}),roles:L.ZL},{key:"4",page:"usage",label:"Old Usage",icon:(0,t.jsx)(x.Z,{})}]}]},{groupLabel:"SETTINGS",roles:L.ZL,items:[{key:"settings",page:"settings",label:(0,t.jsx)("span",{className:"flex items-center gap-4",children:"Settings"}),icon:(0,t.jsx)(I.Z,{}),roles:L.ZL,children:[{key:"router-settings",page:"router-settings",label:"Router Settings",icon:(0,t.jsx)(I.Z,{}),roles:L.ZL},{key:"logging-and-alerts",page:"logging-and-alerts",label:"Logging & Alerts",icon:(0,t.jsx)(I.Z,{}),roles:L.ZL},{key:"admin-panel",page:"admin-panel",label:"Admin Settings",icon:(0,t.jsx)(I.Z,{}),roles:L.ZL},{key:"cost-tracking",page:"cost-tracking",label:"Cost Tracking",icon:(0,t.jsx)(x.Z,{}),roles:L.ZL},{key:"ui-theme",page:"ui-theme",label:"UI Theme",icon:(0,t.jsx)(C.Z,{}),roles:L.ZL}]}]}];s.Z=e=>{let{setPage:s,defaultSelectedKey:l,collapsed:n=!1,enabledPagesInternalUsers:a}=e,{userId:o,accessToken:c,userRole:d}=(0,r.Z)(),{data:u}=(0,i.q)(),m=(0,T.useMemo)(()=>!!o&&!!u&&u.some(e=>{var s;return null===(s=e.members)||void 0===s?void 0:s.some(e=>e.user_id===o&&"org_admin"===e.user_role)}),[o,u]),g=e=>{let l=new URLSearchParams(window.location.search);l.set("page",e),window.history.pushState(null,"","?".concat(l.toString())),s(e)},p=e=>{let s=(0,L.tY)(d);return null!=a&&console.log("[LeftNav] Filtering with enabled pages:",{userRole:d,isAdmin:s,enabledPagesInternalUsers:a}),e.map(e=>({...e,children:e.children?p(e.children):void 0})).filter(e=>{if("organizations"===e.key){if(!(!e.roles||e.roles.includes(d)||m))return!1;if(!s&&null!=a){let s=a.includes(e.page);return console.log('[LeftNav] Page "'.concat(e.page,'" (').concat(e.key,"): ").concat(s?"VISIBLE":"HIDDEN")),s}return!0}if(e.roles&&!e.roles.includes(d))return!1;if(!s&&null!=a){if(e.children&&e.children.length>0&&e.children.some(e=>a.includes(e.page)))return console.log('[LeftNav] Parent "'.concat(e.page,'" (').concat(e.key,"): VISIBLE (has visible children)")),!0;let s=a.includes(e.page);return console.log('[LeftNav] Page "'.concat(e.page,'" (').concat(e.key,"): ").concat(s?"VISIBLE":"HIDDEN")),s}return!0})},x=(e=>{for(let s of R)for(let l of s.items){if(l.page===e)return l.key;if(l.children){let s=l.children.find(s=>s.page===e);if(s)return s.key}}return"api-keys"})(l);return(0,t.jsx)(k.default,{children:(0,t.jsxs)(U,{theme:"light",width:220,collapsed:n,collapsedWidth:80,collapsible:!0,trigger:null,style:{transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",position:"relative"},children:[(0,t.jsx)(O.ZP,{theme:{components:{Menu:{iconSize:15,fontSize:13,itemMarginInline:4,itemPaddingInline:8,itemHeight:30,itemBorderRadius:6,subMenuItemBorderRadius:6,groupTitleFontSize:10,groupTitleLineHeight:1.5}}},children:(0,t.jsx)(E.Z,{mode:"inline",selectedKeys:[x],defaultOpenKeys:[],inlineCollapsed:n,className:"custom-sidebar-menu",style:{borderRight:0,backgroundColor:"transparent",fontSize:"13px",paddingTop:"4px"},items:(()=>{let e=[];return R.forEach(s=>{if(s.roles&&!s.roles.includes(d))return;let l=p(s.items);0!==l.length&&e.push({type:"group",label:n?null:(0,t.jsx)("span",{style:{fontSize:"10px",fontWeight:600,color:"#6b7280",letterSpacing:"0.05em",padding:"12px 0 4px 12px",display:"block",marginBottom:"2px"},children:s.groupLabel}),children:l.map(e=>{var s;return{key:e.key,icon:e.icon,label:e.label,children:null===(s=e.children)||void 0===s?void 0:s.map(e=>({key:e.key,icon:e.icon,label:e.label,onClick:()=>{e.external_url?window.open(e.external_url,"_blank"):g(e.page)}})),onClick:e.children?void 0:()=>{e.external_url?window.open(e.external_url,"_blank"):g(e.page)}}})})}),e})()})}),(0,L.tY)(d)&&!n&&(0,t.jsx)(P.Z,{accessToken:c,width:220})]})})}},79262:function(e,s,l){l.d(s,{Z:function(){return g}});var t=l(57437);l(1309);var i=l(76865),r=l(70525),n=l(95805),a=l(51817),o=l(21047);l(22135),l(40875);var c=l(49663),d=l(2265),u=l(19250);let m=function(){for(var e=arguments.length,s=Array(e),l=0;l{(async()=>{if(s){y(!0),b(null);try{let e=await (0,u.getRemainingUsers)(s);f(e)}catch(e){console.error("Failed to fetch usage data:",e),b("Failed to load usage data")}finally{y(!1)}}})()},[s]);let{isOverLimit:S,isNearLimit:Z,usagePercentage:w,userMetrics:N,teamMetrics:I}=(e=>{if(!e)return{isOverLimit:!1,isNearLimit:!1,usagePercentage:0,userMetrics:{isOverLimit:!1,isNearLimit:!1,usagePercentage:0},teamMetrics:{isOverLimit:!1,isNearLimit:!1,usagePercentage:0}};let s=e.total_users?e.total_users_used/e.total_users*100:0,l=s>100,t=s>=80&&s<=100,i=e.total_teams?e.total_teams_used/e.total_teams*100:0,r=i>100,n=i>=80&&i<=100,a=l||r;return{isOverLimit:a,isNearLimit:(t||n)&&!a,usagePercentage:Math.max(s,i),userMetrics:{isOverLimit:l,isNearLimit:t,usagePercentage:s},teamMetrics:{isOverLimit:r,isNearLimit:n,usagePercentage:i}}})(_),C=()=>S?(0,t.jsx)(i.Z,{className:"h-3 w-3"}):Z?(0,t.jsx)(r.Z,{className:"h-3 w-3"}):null;return s&&((null==_?void 0:_.total_users)!==null||(null==_?void 0:_.total_teams)!==null)?(0,t.jsx)("div",{className:"fixed bottom-4 left-4 z-50",style:{width:"".concat(Math.min(l,220),"px")},children:(0,t.jsx)(()=>x?(0,t.jsx)("button",{onClick:()=>h(!1),className:m("bg-white border border-gray-200 rounded-lg shadow-sm p-3 hover:shadow-md transition-all w-full"),title:"Show usage details",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(n.Z,{className:"h-4 w-4 flex-shrink-0"}),(S||Z)&&(0,t.jsx)("span",{className:"flex-shrink-0",children:C()}),(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium truncate",children:[_&&null!==_.total_users&&(0,t.jsxs)("span",{className:m("flex-shrink-0 px-1.5 py-0.5 rounded text-xs border",N.isOverLimit&&"bg-red-50 text-red-700 border-red-200",N.isNearLimit&&"bg-yellow-50 text-yellow-700 border-yellow-200",!N.isOverLimit&&!N.isNearLimit&&"bg-gray-50 text-gray-700 border-gray-200"),children:["U: ",_.total_users_used,"/",_.total_users]}),_&&null!==_.total_teams&&(0,t.jsxs)("span",{className:m("flex-shrink-0 px-1.5 py-0.5 rounded text-xs border",I.isOverLimit&&"bg-red-50 text-red-700 border-red-200",I.isNearLimit&&"bg-yellow-50 text-yellow-700 border-yellow-200",!I.isOverLimit&&!I.isNearLimit&&"bg-gray-50 text-gray-700 border-gray-200"),children:["T: ",_.total_teams_used,"/",_.total_teams]}),!_||null===_.total_users&&null===_.total_teams&&(0,t.jsx)("span",{className:"truncate",children:"Usage"})]})]})}):j?(0,t.jsx)("div",{className:"bg-white border border-gray-200 rounded-lg shadow-sm p-4 w-full",children:(0,t.jsxs)("div",{className:"flex items-center justify-center gap-2 py-2",children:[(0,t.jsx)(a.Z,{className:"h-4 w-4 animate-spin"}),(0,t.jsx)("span",{className:"text-sm text-gray-500 truncate",children:"Loading..."})]})}):v||!_?(0,t.jsx)("div",{className:"bg-white border border-gray-200 rounded-lg shadow-sm p-4 group w-full",children:(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("div",{className:"flex-1 min-w-0",children:(0,t.jsx)("span",{className:"text-sm text-gray-500 truncate block",children:v||"No data"})}),(0,t.jsx)("button",{onClick:()=>h(!0),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-gray-100 rounded transition-all flex-shrink-0",title:"Minimize",children:(0,t.jsx)(o.Z,{className:"h-3 w-3 text-gray-400"})})]})}):(0,t.jsxs)("div",{className:m("bg-white border rounded-lg shadow-sm p-3 transition-all duration-200 group w-full"),children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 mb-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[(0,t.jsx)(n.Z,{className:"h-4 w-4 flex-shrink-0"}),(0,t.jsx)("span",{className:"font-medium text-sm truncate",children:"Usage"})]}),(0,t.jsx)("button",{onClick:()=>h(!0),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-gray-100 rounded transition-all flex-shrink-0",title:"Minimize",children:(0,t.jsx)(o.Z,{className:"h-3 w-3 text-gray-400"})})]}),(0,t.jsxs)("div",{className:"space-y-3 text-sm",children:[null!==_.total_users&&(0,t.jsxs)("div",{className:m("space-y-1 border rounded-md p-2",N.isOverLimit&&"border-red-200 bg-red-50",N.isNearLimit&&"border-yellow-200 bg-yellow-50"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-xs text-gray-600 mb-1",children:[(0,t.jsx)(n.Z,{className:"h-3 w-3"}),(0,t.jsx)("span",{className:"font-medium",children:"Users"}),(0,t.jsx)("span",{className:m("ml-1 px-1.5 py-0.5 rounded border",N.isOverLimit&&"bg-red-50 text-red-700 border-red-200",N.isNearLimit&&"bg-yellow-50 text-yellow-700 border-yellow-200",!N.isOverLimit&&!N.isNearLimit&&"bg-gray-50 text-gray-600 border-gray-200"),children:N.isOverLimit?"Over limit":N.isNearLimit?"Near limit":"OK"})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{className:"text-gray-600 text-xs",children:"Used:"}),(0,t.jsxs)("span",{className:"font-medium text-right",children:[_.total_users_used,"/",_.total_users]})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{className:"text-gray-600 text-xs",children:"Remaining:"}),(0,t.jsx)("span",{className:m("font-medium text-right",N.isOverLimit&&"text-red-600",N.isNearLimit&&"text-yellow-600"),children:_.total_users_remaining})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{className:"text-gray-600 text-xs",children:"Usage:"}),(0,t.jsxs)("span",{className:"font-medium text-right",children:[Math.round(N.usagePercentage),"%"]})]}),(0,t.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-2",children:(0,t.jsx)("div",{className:m("h-2 rounded-full transition-all duration-300",N.isOverLimit&&"bg-red-500",N.isNearLimit&&"bg-yellow-500",!N.isOverLimit&&!N.isNearLimit&&"bg-green-500"),style:{width:"".concat(Math.min(N.usagePercentage,100),"%")}})})]}),null!==_.total_teams&&(0,t.jsxs)("div",{className:m("space-y-1 border rounded-md p-2",I.isOverLimit&&"border-red-200 bg-red-50",I.isNearLimit&&"border-yellow-200 bg-yellow-50"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-xs text-gray-600 mb-1",children:[(0,t.jsx)(c.Z,{className:"h-3 w-3"}),(0,t.jsx)("span",{className:"font-medium",children:"Teams"}),(0,t.jsx)("span",{className:m("ml-1 px-1.5 py-0.5 rounded border",I.isOverLimit&&"bg-red-50 text-red-700 border-red-200",I.isNearLimit&&"bg-yellow-50 text-yellow-700 border-yellow-200",!I.isOverLimit&&!I.isNearLimit&&"bg-gray-50 text-gray-600 border-gray-200"),children:I.isOverLimit?"Over limit":I.isNearLimit?"Near limit":"OK"})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{className:"text-gray-600 text-xs",children:"Used:"}),(0,t.jsxs)("span",{className:"font-medium text-right",children:[_.total_teams_used,"/",_.total_teams]})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{className:"text-gray-600 text-xs",children:"Remaining:"}),(0,t.jsx)("span",{className:m("font-medium text-right",I.isOverLimit&&"text-red-600",I.isNearLimit&&"text-yellow-600"),children:_.total_teams_remaining})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{className:"text-gray-600 text-xs",children:"Usage:"}),(0,t.jsxs)("span",{className:"font-medium text-right",children:[Math.round(I.usagePercentage),"%"]})]}),(0,t.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-2",children:(0,t.jsx)("div",{className:m("h-2 rounded-full transition-all duration-300",I.isOverLimit&&"bg-red-500",I.isNearLimit&&"bg-yellow-500",!I.isOverLimit&&!I.isNearLimit&&"bg-green-500"),style:{width:"".concat(Math.min(I.usagePercentage,100),"%")}})})]})]})]}),{})}):null}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1878-9839899cc1d1c214.js b/litellm/proxy/_experimental/out/_next/static/chunks/1878-9839899cc1d1c214.js new file mode 100644 index 00000000000..f00767cffa6 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1878-9839899cc1d1c214.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1878],{44803:function(e,s,r){r.d(s,{Dx:function(){return a.Z},Zb:function(){return t.Z},xv:function(){return l.Z}});var t=r(12514),l=r(84264),a=r(96761)},61878:function(e,s,r){r.d(s,{d:function(){return sv},o:function(){return sZ}});var t=r(57437),l=r(20347),a=r(67187),n=r(78489),i=r(12485),o=r(18135),c=r(35242),d=r(29706),m=r(77991),u=r(84264),x=r(96761),h=r(57840),p=r(37592),g=r(22116),j=r(76188),v=r(99981),f=r(2265),y=r(68474),b=r(11713),N=r(90246),_=r(19250),w=r(80443);let Z=(0,N.n)("mcpServerHealth"),C=e=>{let{accessToken:s}=(0,w.Z)();return(0,b.a)({queryKey:[...Z.lists(),{serverIds:e}],queryFn:async()=>await (0,_.fetchMCPServerHealth)(s,e),enabled:!!s,refetchInterval:3e4})};var S=r(9114),k=r(60493),P=r(10032),A=r(4260),T=r(15424),I=r(64504);let M={NONE:"none",API_KEY:"api_key",BEARER_TOKEN:"bearer_token",BASIC:"basic",OAUTH2:"oauth2"},E={SSE:"sse"},O=e=>(console.log(e),null==e)?E.SSE:e,L=e=>null==e?M.NONE:e;var z=r(12221),F=r(44851),q=r(33866),R=r(62670),U=r(58630),V=r(44803),B=e=>{let{value:s={},onChange:r,tools:l=[],disabled:a=!1}=e,n=(e,t)=>{let l={...s,tool_name_to_cost_per_query:{...s.tool_name_to_cost_per_query,[e]:t}};null==r||r(l)};return(0,t.jsx)(V.Zb,{children:(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,t.jsx)(R.Z,{className:"text-green-600"}),(0,t.jsx)(V.Dx,{children:"Cost Configuration"}),(0,t.jsx)(v.Z,{title:"Configure costs for this MCP server's tool calls. Set a default rate and per-tool overrides.",children:(0,t.jsx)(T.Z,{className:"text-gray-400"})})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:["Default Cost per Query ($)",(0,t.jsx)(v.Z,{title:"Default cost charged for each tool call to this server.",children:(0,t.jsx)(T.Z,{className:"ml-1 text-gray-400"})})]}),(0,t.jsx)(z.Z,{min:0,step:1e-4,precision:4,placeholder:"0.0000",value:s.default_cost_per_query,onChange:e=>{let t={...s,default_cost_per_query:e};null==r||r(t)},disabled:a,style:{width:"200px"},addonBefore:"$"}),(0,t.jsx)(V.xv,{className:"block mt-1 text-gray-500 text-sm",children:"Set a default cost for all tool calls to this server"})]}),l.length>0&&(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("label",{className:"block text-sm font-medium text-gray-700",children:["Tool-Specific Costs ($)",(0,t.jsx)(v.Z,{title:"Override the default cost for specific tools. Leave blank to use the default rate.",children:(0,t.jsx)(T.Z,{className:"ml-1 text-gray-400"})})]}),(0,t.jsx)(F.default,{items:[{key:"1",label:(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(U.Z,{className:"mr-2 text-blue-500"}),(0,t.jsx)("span",{className:"font-medium",children:"Available Tools"}),(0,t.jsx)(q.Z,{count:l.length,style:{backgroundColor:"#52c41a",marginLeft:"8px"}})]}),children:(0,t.jsx)("div",{className:"space-y-3 max-h-64 overflow-y-auto",children:l.map((e,r)=>{var l;return(0,t.jsxs)("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(V.xv,{className:"font-medium text-gray-900",children:e.name}),e.description&&(0,t.jsx)(V.xv,{className:"text-gray-500 text-sm block mt-1",children:e.description})]}),(0,t.jsx)("div",{className:"ml-4",children:(0,t.jsx)(z.Z,{min:0,step:1e-4,precision:4,placeholder:"Use default",value:null===(l=s.tool_name_to_cost_per_query)||void 0===l?void 0:l[e.name],onChange:s=>n(e.name,s),disabled:a,style:{width:"120px"},addonBefore:"$"})})]},r)})})}]})]})]}),(s.default_cost_per_query||s.tool_name_to_cost_per_query&&Object.keys(s.tool_name_to_cost_per_query).length>0)&&(0,t.jsxs)("div",{className:"mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:[(0,t.jsx)(V.xv,{className:"text-blue-800 font-medium",children:"Cost Summary:"}),(0,t.jsxs)("div",{className:"mt-2 space-y-1",children:[s.default_cost_per_query&&(0,t.jsxs)(V.xv,{className:"text-blue-700",children:["• Default cost: $",s.default_cost_per_query.toFixed(4)," per query"]}),s.tool_name_to_cost_per_query&&Object.entries(s.tool_name_to_cost_per_query).map(e=>{let[s,r]=e;return null!=r&&(0,t.jsxs)(V.xv,{className:"text-blue-700",children:["• ",s,": $",r.toFixed(4)," per query"]},s)})]})]})]})})},D=r(10353),K=r(51653),H=r(5545),J=r(83669),G=r(29271),Y=r(89245);let W=e=>{var s,r;let{accessToken:t,oauthAccessToken:l,formValues:a,enabled:n=!0}=e,[i,o]=(0,f.useState)([]),[c,d]=(0,f.useState)(!1),[m,u]=(0,f.useState)(null),[x,h]=(0,f.useState)(null),[p,g]=(0,f.useState)(!1),j=a.auth_type===M.OAUTH2,v=!!(a.url&&a.transport&&a.auth_type&&t&&(!j||l)),y=JSON.stringify(null!==(s=a.static_headers)&&void 0!==s?s:{}),b=JSON.stringify(null!==(r=a.credentials)&&void 0!==r?r:{}),N=async()=>{if(t&&a.url&&(!j||l)){d(!0),u(null);try{let e=Array.isArray(a.static_headers)?a.static_headers.reduce((e,s)=>{var r;let t=null==s?void 0:null===(r=s.header)||void 0===r?void 0:r.trim();return t&&(e[t]=(null==s?void 0:s.value)!=null?String(s.value):""),e},{}):!Array.isArray(a.static_headers)&&a.static_headers&&"object"==typeof a.static_headers?Object.entries(a.static_headers).reduce((e,s)=>{let[r,t]=s;return r&&(e[r]=null!=t?String(t):""),e},{}):{},s=a.credentials&&"object"==typeof a.credentials?Object.entries(a.credentials).reduce((e,s)=>{let[r,t]=s;if(null==t||""===t)return e;if("scopes"===r){if(Array.isArray(t)){let s=t.filter(e=>null!=e&&""!==e);s.length>0&&(e[r]=s)}}else e[r]=t;return e},{}):void 0,r={server_id:a.server_id||"",server_name:a.server_name||"",url:a.url,transport:a.transport,auth_type:a.auth_type,authorization_url:a.authorization_url,token_url:a.token_url,registration_url:a.registration_url,mcp_info:a.mcp_info,static_headers:e};s&&Object.keys(s).length>0&&(r.credentials=s);let n=await (0,_.testMCPToolsListRequest)(t,r,l);if(n.tools&&!n.error)o(n.tools),u(null),h(null),n.tools.length>0&&!p&&g(!0);else{let e=n.message||"Failed to retrieve tools list";u(e),h(n.stack_trace||null),o([]),g(!1)}}catch(e){console.error("Tools fetch error:",e),u(e instanceof Error?e.message:String(e)),h(null),o([]),g(!1)}finally{d(!1)}}},w=()=>{o([]),u(null),h(null),g(!1)};return(0,f.useEffect)(()=>{n&&(v?N():w())},[a.url,a.transport,a.auth_type,t,n,l,v,y,b]),{tools:i,isLoadingTools:c,toolsError:m,toolsErrorStackTrace:x,hasShownSuccessMessage:p,canFetchTools:v,fetchTools:N,clearTools:w}};var $=e=>{let{accessToken:s,oauthAccessToken:r,formValues:l,onToolsLoaded:a}=e,{tools:n,isLoadingTools:i,toolsError:o,toolsErrorStackTrace:c,canFetchTools:d,fetchTools:m}=W({accessToken:s,oauthAccessToken:r,formValues:l,enabled:!0});return((0,f.useEffect)(()=>{null==a||a(n)},[n,a]),d||l.url)?(0,t.jsx)(V.Zb,{children:(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(J.Z,{className:"text-blue-600"}),(0,t.jsx)(V.Dx,{children:"Connection Status"})]}),!d&&l.url&&(0,t.jsxs)("div",{className:"text-center py-6 text-gray-400 border rounded-lg border-dashed",children:[(0,t.jsx)(U.Z,{className:"text-2xl mb-2"}),(0,t.jsx)(V.xv,{children:"Complete required fields to test connection"}),(0,t.jsx)("br",{}),(0,t.jsx)(V.xv,{className:"text-sm",children:"Fill in URL, Transport, and Authentication to test MCP server connection"})]}),d&&(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(V.xv,{className:"text-gray-700 font-medium",children:i?"Testing connection to MCP server...":n.length>0?"Connection successful":o?"Connection failed":"Ready to test connection"}),(0,t.jsx)("br",{}),(0,t.jsxs)(V.xv,{className:"text-gray-500 text-sm",children:["Server: ",l.url]})]}),i&&(0,t.jsxs)("div",{className:"flex items-center text-blue-600",children:[(0,t.jsx)(D.Z,{size:"small",className:"mr-2"}),(0,t.jsx)(V.xv,{className:"text-blue-600",children:"Connecting..."})]}),!i&&!o&&n.length>0&&(0,t.jsxs)("div",{className:"flex items-center text-green-600",children:[(0,t.jsx)(J.Z,{className:"mr-1"}),(0,t.jsx)(V.xv,{className:"text-green-600 font-medium",children:"Connected"})]}),o&&(0,t.jsxs)("div",{className:"flex items-center text-red-600",children:[(0,t.jsx)(G.Z,{className:"mr-1"}),(0,t.jsx)(V.xv,{className:"text-red-600 font-medium",children:"Failed"})]})]}),i&&(0,t.jsxs)("div",{className:"flex items-center justify-center py-6",children:[(0,t.jsx)(D.Z,{size:"large"}),(0,t.jsx)(V.xv,{className:"ml-3",children:"Testing connection and loading tools..."})]}),o&&(0,t.jsx)(K.Z,{message:"Connection Failed",description:(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{children:o}),c&&(0,t.jsx)(F.default,{items:[{key:"stack-trace",label:"Stack Trace",children:(0,t.jsx)("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:"12px",fontFamily:"monospace",margin:0,padding:"8px",backgroundColor:"#f5f5f5",borderRadius:"4px",maxHeight:"400px",overflow:"auto"},children:c})}],style:{marginTop:"12px"}})]}),type:"error",showIcon:!0,action:(0,t.jsx)(H.ZP,{icon:(0,t.jsx)(Y.Z,{}),onClick:m,size:"small",children:"Retry"})}),!i&&0===n.length&&!o&&(0,t.jsxs)("div",{className:"text-center py-6 text-gray-500 border rounded-lg border-dashed",children:[(0,t.jsx)(J.Z,{className:"text-2xl mb-2 text-green-500"}),(0,t.jsx)(V.xv,{className:"text-green-600 font-medium",children:"Connection successful!"}),(0,t.jsx)("br",{}),(0,t.jsx)(V.xv,{className:"text-gray-500",children:"No tools found for this MCP server"})]})]})]})}):null},Q=r(4156),X=e=>{let{accessToken:s,oauthAccessToken:r,formValues:l,allowedTools:a,existingAllowedTools:n,onAllowedToolsChange:i}=e,o=(0,f.useRef)(0),{tools:c,isLoadingTools:d,toolsError:m,canFetchTools:u}=W({accessToken:s,oauthAccessToken:r,formValues:l,enabled:!0});(0,f.useEffect)(()=>{if(c.length>0&&c.length!==o.current&&0===a.length){if(n&&n.length>0){let e=c.map(e=>e.name);i(n.filter(s=>e.includes(s)))}else i(c.map(e=>e.name))}o.current=c.length},[c,a.length,n,i]);let x=e=>{a.includes(e)?i(a.filter(s=>s!==e)):i([...a,e])};return u||l.url?(0,t.jsx)(V.Zb,{children:(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"flex items-center justify-between",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(U.Z,{className:"text-blue-600"}),(0,t.jsx)(V.Dx,{children:"Tool Configuration"}),c.length>0&&(0,t.jsx)(q.Z,{count:c.length,style:{backgroundColor:"#52c41a"}})]})}),(0,t.jsx)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:(0,t.jsxs)(V.xv,{className:"text-blue-800 text-sm",children:[(0,t.jsx)("strong",{children:"Select which tools users can call:"})," Only checked tools will be available for users to invoke. Unchecked tools will be blocked from execution."]})}),d&&(0,t.jsxs)("div",{className:"flex items-center justify-center py-6",children:[(0,t.jsx)(D.Z,{size:"large"}),(0,t.jsx)(V.xv,{className:"ml-3",children:"Loading tools..."})]}),m&&!d&&(0,t.jsxs)("div",{className:"text-center py-6 text-red-500 border rounded-lg border-dashed border-red-300 bg-red-50",children:[(0,t.jsx)(U.Z,{className:"text-2xl mb-2"}),(0,t.jsx)(V.xv,{className:"text-red-600 font-medium",children:"Unable to load tools"}),(0,t.jsx)("br",{}),(0,t.jsx)(V.xv,{className:"text-sm text-red-500",children:m})]}),!d&&!m&&0===c.length&&u&&(0,t.jsxs)("div",{className:"text-center py-6 text-gray-400 border rounded-lg border-dashed",children:[(0,t.jsx)(U.Z,{className:"text-2xl mb-2"}),(0,t.jsx)(V.xv,{children:"No tools available for configuration"}),(0,t.jsx)("br",{}),(0,t.jsx)(V.xv,{className:"text-sm",children:"Connect to an MCP server with tools to configure them"})]}),!u&&l.url&&(0,t.jsxs)("div",{className:"text-center py-6 text-gray-400 border rounded-lg border-dashed",children:[(0,t.jsx)(U.Z,{className:"text-2xl mb-2"}),(0,t.jsx)(V.xv,{children:"Complete required fields to configure tools"}),(0,t.jsx)("br",{}),(0,t.jsx)(V.xv,{className:"text-sm",children:"Fill in URL, Transport, and Authentication to load available tools"})]}),!d&&!m&&c.length>0&&(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-green-50 rounded-lg border border-green-200 flex-1",children:[(0,t.jsx)(J.Z,{className:"text-green-600"}),(0,t.jsxs)(V.xv,{className:"text-green-700 font-medium",children:[a.length," of ",c.length," ",1===c.length?"tool":"tools"," enabled for user access"]})]}),(0,t.jsxs)("div",{className:"flex gap-2 ml-3",children:[(0,t.jsx)("button",{type:"button",onClick:()=>{i(c.map(e=>e.name))},className:"px-3 py-1.5 text-sm text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-md transition-colors",children:"Enable All"}),(0,t.jsx)("button",{type:"button",onClick:()=>{i([])},className:"px-3 py-1.5 text-sm text-gray-600 hover:text-gray-700 hover:bg-gray-100 rounded-md transition-colors",children:"Disable All"})]})]}),(0,t.jsx)("div",{className:"space-y-2",children:c.map((e,s)=>(0,t.jsx)("div",{className:"p-4 rounded-lg border transition-colors cursor-pointer ".concat(a.includes(e.name)?"bg-blue-50 border-blue-300 hover:border-blue-400":"bg-gray-50 border-gray-200 hover:border-gray-300"),onClick:()=>x(e.name),children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Q.Z,{checked:a.includes(e.name),onChange:()=>x(e.name)}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(V.xv,{className:"font-medium text-gray-900",children:e.name}),(0,t.jsx)("span",{className:"px-2 py-0.5 text-xs rounded-full font-medium ".concat(a.includes(e.name)?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:a.includes(e.name)?"Enabled":"Disabled"})]}),e.description&&(0,t.jsx)(V.xv,{className:"text-gray-500 text-sm block mt-1",children:e.description}),(0,t.jsx)(V.xv,{className:"text-gray-400 text-xs block mt-1",children:a.includes(e.name)?"✓ Users can call this tool":"✗ Users cannot call this tool"})]})]})},s))})]})]})}):null},ee=e=>{let{isVisible:s}=e;return s?(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Stdio Configuration (JSON)",(0,t.jsx)(v.Z,{title:"Paste your stdio MCP server configuration in JSON format. You can use the full mcpServers structure from config.yaml or just the inner server configuration.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"stdio_config",rules:[{required:!0,message:"Please enter stdio configuration"},{validator:(e,s)=>{if(!s)return Promise.resolve();try{return JSON.parse(s),Promise.resolve()}catch(e){return Promise.reject("Please enter valid JSON")}}}],children:(0,t.jsx)(A.default.TextArea,{placeholder:'{\n "mcpServers": {\n "circleci-mcp-server": {\n "command": "npx",\n "args": ["-y", "@circleci/mcp-server-circleci"],\n "env": {\n "CIRCLECI_TOKEN": "your-circleci-token",\n "CIRCLECI_BASE_URL": "https://circleci.com"\n }\n }\n }\n}',rows:12,className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500 font-mono text-sm"})}):null},es=r(63709),er=r(55590),et=r(45246),el=r(96473);let{Panel:ea}=F.default;var en=e=>{var s,r;let{availableAccessGroups:l,mcpServer:a,searchValue:n,setSearchValue:i,getAccessGroupOptions:o}=e,c=P.Z.useFormInstance();return(0,f.useEffect)(()=>{if(a){if(a.extra_headers&&c.setFieldValue("extra_headers",a.extra_headers),a.static_headers){let e=Object.entries(a.static_headers).map(e=>{let[s,r]=e;return{header:s,value:null!=r?String(r):""}});c.setFieldValue("static_headers",e)}"boolean"==typeof a.allow_all_keys&&c.setFieldValue("allow_all_keys",a.allow_all_keys),"boolean"==typeof a.available_on_public_internet&&c.setFieldValue("available_on_public_internet",a.available_on_public_internet)}else c.setFieldValue("allow_all_keys",!1),c.setFieldValue("available_on_public_internet",!1)},[a,c]),(0,t.jsx)(F.default,{className:"bg-gray-50 border border-gray-200 rounded-lg",expandIconPosition:"end",ghost:!1,children:(0,t.jsx)(ea,{header:(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full"}),(0,t.jsx)("h3",{className:"text-lg font-semibold text-gray-900",children:"Permission Management / Access Control"})]}),(0,t.jsx)("p",{className:"text-sm text-gray-600 ml-4",children:"Configure access permissions and security settings (Optional)"})]}),className:"border-0",children:(0,t.jsxs)("div",{className:"space-y-6 pt-4",children:[(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Allow All LiteLLM Keys",(0,t.jsx)(v.Z,{title:"When enabled, every API key can access this MCP server.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),(0,t.jsx)("p",{className:"text-sm text-gray-600 mt-1",children:'Enable if this server should be "public" to all keys.'})]}),(0,t.jsx)(P.Z.Item,{name:"allow_all_keys",valuePropName:"checked",initialValue:null!==(s=null==a?void 0:a.allow_all_keys)&&void 0!==s&&s,className:"mb-0",children:(0,t.jsx)(es.Z,{})})]}),(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Available on Public Internet",(0,t.jsx)(v.Z,{title:"When enabled, this MCP server is accessible from external/public IPs (e.g., ChatGPT). When disabled, only callers from internal/private networks can access it.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),(0,t.jsx)("p",{className:"text-sm text-gray-600 mt-1",children:"Enable if this server should be reachable from the public internet."})]}),(0,t.jsx)(P.Z.Item,{name:"available_on_public_internet",valuePropName:"checked",initialValue:null!==(r=null==a?void 0:a.available_on_public_internet)&&void 0!==r&&r,className:"mb-0",children:(0,t.jsx)(es.Z,{})})]}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["MCP Access Groups",(0,t.jsx)(v.Z,{title:"Specify access groups for this MCP server. Users must be in at least one of these groups to access the server.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"mcp_access_groups",className:"mb-4",children:(0,t.jsx)(p.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"value",filterOption:(e,s)=>{var r;return(null!==(r=null==s?void 0:s.value)&&void 0!==r?r:"").toLowerCase().includes(e.toLowerCase())},onSearch:e=>i(e),tokenSeparators:[","],options:o(),maxTagCount:"responsive",allowClear:!0})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Extra Headers",(0,t.jsx)(v.Z,{title:"Forward custom headers from incoming requests to this MCP server (e.g., Authorization, X-Custom-Header, User-Agent)",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})}),(null==a?void 0:a.extra_headers)&&a.extra_headers.length>0&&(0,t.jsxs)("span",{className:"ml-2 text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full",children:[a.extra_headers.length," configured"]})]}),name:"extra_headers",children:(0,t.jsx)(p.default,{mode:"tags",placeholder:(null==a?void 0:a.extra_headers)&&a.extra_headers.length>0?"Currently: ".concat(a.extra_headers.join(", ")):"Enter header names (e.g., Authorization, X-Custom-Header)",className:"rounded-lg",size:"large",tokenSeparators:[","],allowClear:!0})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Static Headers",(0,t.jsx)(v.Z,{title:"Send these key-value headers with every request to this MCP server.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),required:!1,children:(0,t.jsx)(P.Z.List,{name:"static_headers",children:(e,s)=>{let{add:r,remove:l}=s;return(0,t.jsxs)("div",{className:"space-y-3",children:[e.map(e=>{let{key:s,name:r,...a}=e;return(0,t.jsxs)(er.Z,{className:"flex w-full",align:"baseline",size:"middle",children:[(0,t.jsx)(P.Z.Item,{...a,name:[r,"header"],className:"flex-1",rules:[{required:!0,message:"Header name is required"}],children:(0,t.jsx)(A.default,{size:"large",allowClear:!0,className:"rounded-lg",placeholder:"Header name (e.g., X-API-Key)"})}),(0,t.jsx)(P.Z.Item,{...a,name:[r,"value"],className:"flex-1",rules:[{required:!0,message:"Header value is required"}],children:(0,t.jsx)(A.default,{size:"large",allowClear:!0,className:"rounded-lg",placeholder:"Header value"})}),(0,t.jsx)(et.Z,{onClick:()=>l(r),className:"text-gray-500 hover:text-red-500 cursor-pointer"})]},s)}),(0,t.jsx)(H.ZP,{type:"dashed",onClick:()=>r(),icon:(0,t.jsx)(el.Z,{}),block:!0,children:"Add Static Header"})]})}})})]})},"permissions")})};let ei=e=>{try{let s=e.indexOf("/mcp/");if(-1===s)return{token:null,baseUrl:e};let r=e.split("/mcp/");if(2!==r.length)return{token:null,baseUrl:e};let t=r[0]+"/mcp/",l=r[1];if(!l)return{token:null,baseUrl:e};return{token:l,baseUrl:t}}catch(s){return console.error("Error parsing MCP URL:",s),{token:null,baseUrl:e}}},eo=e=>{let{token:s,baseUrl:r}=ei(e);return s?r+"...":e},ec=e=>{let{token:s}=ei(e);return{maskedUrl:eo(e),hasToken:!!s}},ed=e=>e?/^https?:\/\/[^\s/$.?#].[^\s]*$/i.test(e)?Promise.resolve():Promise.reject("Please enter a valid URL (e.g., http://service-name.domain:1234/path or https://example.com)"):Promise.resolve(),em=e=>e&&e.includes("-")?Promise.reject("Server name cannot contain '-' (hyphen). Please use '_' (underscore) instead."):Promise.resolve(),eu=e=>{let s=new Uint8Array(e),r="";return s.forEach(e=>r+=String.fromCharCode(e)),btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},ex=()=>{let e=new Uint8Array(32);return window.crypto.getRandomValues(e),eu(e.buffer)},eh=async e=>{let s=new TextEncoder().encode(e);return eu(await window.crypto.subtle.digest("SHA-256",s))},ep=e=>{let{accessToken:s,getCredentials:r,getTemporaryPayload:t,onTokenReceived:l,onBeforeRedirect:a}=e,[n,i]=(0,f.useState)("idle"),[o,c]=(0,f.useState)(null),[d,m]=(0,f.useState)(null),u="litellm-mcp-oauth-flow-state",x="litellm-mcp-oauth-result",h="litellm-mcp-oauth-return-url",p=()=>{try{window.sessionStorage.removeItem(u),window.sessionStorage.removeItem(x),window.sessionStorage.removeItem(h)}catch(e){console.warn("Failed to clear OAuth storage",e)}},g=()=>{{let e=window.location.pathname||"",s=e.indexOf("/ui"),r=(s>=0?e.slice(0,s+3):"").replace(/\/+$/,"");return"".concat(window.location.origin).concat(r,"/mcp/oauth/callback")}},j=()=>g(),v=(0,f.useCallback)(async()=>{let e=r()||{};if(!s){c("Missing admin token"),S.ZP.error("Access token missing. Please re-authenticate and try again.");return}let l=t();if(!l||!l.url||!l.transport){let e="Please complete server URL and transport before starting OAuth.";c(e),S.ZP.error(e);return}try{var n,o,d;i("authorizing"),c(null);let r=await (0,_.cacheTemporaryMcpServer)(s,l),t=null==r?void 0:null===(n=r.server_id)||void 0===n?void 0:n.trim();if(!t)throw Error("Temporary MCP server identifier missing. Please retry.");let m={};if(!((null===(o=l.credentials)||void 0===o?void 0:o.client_id)&&(null===(d=l.credentials)||void 0===d?void 0:d.client_secret))){let e=await (0,_.registerMcpOAuthClient)(s,t,{client_name:l.alias||l.server_name||t,grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:l.credentials&&l.credentials.client_secret?"client_secret_post":"none"});m={clientId:null==e?void 0:e.client_id,clientSecret:null==e?void 0:e.client_secret}}let x=ex(),p=await eh(x),g=crypto.randomUUID(),v=m.clientId||e.client_id,f=Array.isArray(e.scopes)?e.scopes.filter(e=>e&&e.trim().length>0).join(" "):void 0,y=(0,_.buildMcpOAuthAuthorizeUrl)({serverId:t,clientId:v,redirectUri:j(),state:g,codeChallenge:p,scope:f}),b={state:g,codeVerifier:x,clientId:v,clientSecret:m.clientSecret||e.client_secret,serverId:t,redirectUri:j()};if(a)try{a()}catch(e){console.error("Failed to prepare for OAuth redirect",e)}try{window.sessionStorage.setItem(u,JSON.stringify(b)),window.sessionStorage.setItem(h,window.location.href)}catch(e){throw console.error("Unable to persist OAuth state",e),Error("Unable to access browser storage for OAuth. Please enable storage and retry.")}window.location.href=y}catch(s){console.error("Failed to start OAuth flow",s),i("error");let e=s instanceof Error?s.message:String(s);c(e),S.ZP.error(e)}},[s,r,t,a]),y=(0,f.useCallback)(async()=>{let e=null,s=null;try{let r=window.sessionStorage.getItem(x);if(!r)return;e=JSON.parse(r),s=JSON.parse(window.sessionStorage.getItem(u)||"null")}catch(e){console.error("Failed to read OAuth session state",e),p(),c("Failed to resume OAuth flow. Please retry."),i("error"),S.ZP.error("Failed to resume OAuth flow. Please retry.");return}if(e){window.sessionStorage.removeItem(x);try{if(!s||!s.state||!s.codeVerifier||!s.serverId)throw Error("Missing OAuth session state. Please retry.");if(!e.state||e.state!==s.state)throw Error("OAuth state mismatch. Please retry.");if(e.error)throw Error(e.error_description||e.error);if(!e.code)throw Error("Authorization code missing in callback.");i("exchanging");let r=await (0,_.exchangeMcpOAuthToken)({serverId:s.serverId,code:e.code,clientId:s.clientId,clientSecret:s.clientSecret,codeVerifier:s.codeVerifier,redirectUri:s.redirectUri});l(r),m(r),i("success"),c(null),S.ZP.success("OAuth token retrieved successfully")}catch(s){console.error("OAuth flow failed",s);let e=s instanceof Error?s.message:String(s);c(e),i("error"),S.ZP.error(e)}finally{p()}}},[l]);return(0,f.useEffect)(()=>{let e=!1;return(async()=>{e||await y()})(),()=>{e=!0}},[y]),{startOAuthFlow:v,status:n,error:o,tokenResponse:d}},eg="".concat("../ui/assets/logos/","mcp_logo.png"),ej=[M.API_KEY,M.BEARER_TOKEN,M.BASIC],ev=[...ej,M.OAUTH2],ef="litellm-mcp-oauth-create-state";var ey=e=>{var s;let{userRole:r,accessToken:a,onCreateSuccess:n,isModalVisible:i,setModalVisible:o,availableAccessGroups:c}=e,[d]=P.Z.useForm(),[m,u]=(0,f.useState)(!1),[x,h]=(0,f.useState)({}),[j,y]=(0,f.useState)({}),[b,N]=(0,f.useState)(null),[w,Z]=(0,f.useState)(!1),[C,k]=(0,f.useState)([]),[E,O]=(0,f.useState)([]),[L,z]=(0,f.useState)(""),[F,q]=(0,f.useState)(""),[R,U]=(0,f.useState)(null),V=j.auth_type,D=!!V&&ej.includes(V),K=V===M.OAUTH2,{startOAuthFlow:H,status:J,error:G,tokenResponse:Y}=ep({accessToken:a,getCredentials:()=>d.getFieldValue("credentials"),getTemporaryPayload:()=>{let e=d.getFieldsValue(!0),s=e.url,r=e.transport||L;if(!s||!r)return null;let t=Array.isArray(e.static_headers)?e.static_headers.reduce((e,s)=>{var r,t;let l=null==s?void 0:null===(r=s.header)||void 0===r?void 0:r.trim();return l&&(e[l]=null!==(t=null==s?void 0:s.value)&&void 0!==t?t:""),e},{}):{};return{server_id:void 0,server_name:e.server_name,alias:e.alias,description:e.description,url:s,transport:r,auth_type:M.OAUTH2,credentials:e.credentials,authorization_url:e.authorization_url,token_url:e.token_url,registration_url:e.registration_url,mcp_access_groups:e.mcp_access_groups,static_headers:t,command:e.command,args:e.args,env:e.env}},onTokenReceived:e=>{var s;U(null!==(s=null==e?void 0:e.access_token)&&void 0!==s?s:null)},onBeforeRedirect:()=>{try{let e=d.getFieldsValue(!0);window.sessionStorage.setItem(ef,JSON.stringify({modalVisible:i,formValues:e,transportType:L,costConfig:x,allowedTools:E,searchValue:F,aliasManuallyEdited:w}))}catch(e){console.warn("Failed to persist MCP create state",e)}}});f.useEffect(()=>{let e=window.sessionStorage.getItem(ef);if(e)try{var s;let r=JSON.parse(e);r.modalVisible&&o(!0);let t=(null===(s=r.formValues)||void 0===s?void 0:s.transport)||r.transportType||"";t&&z(t),r.formValues&&N({values:r.formValues,transport:t}),r.costConfig&&h(r.costConfig),r.allowedTools&&O(r.allowedTools),r.searchValue&&q(r.searchValue),"boolean"==typeof r.aliasManuallyEdited&&Z(r.aliasManuallyEdited)}catch(e){console.error("Failed to restore MCP create state",e)}finally{window.sessionStorage.removeItem(ef)}},[d,o]),f.useEffect(()=>{b&&(L||b.transport,(!b.transport||L)&&(d.setFieldsValue(b.values),y(b.values),N(null)))},[b,d,L]);let W=async e=>{u(!0);try{let{static_headers:s,stdio_config:r,credentials:t,allow_all_keys:l,available_on_public_internet:i,...c}=e,m=c.mcp_access_groups,u=Array.isArray(s)?s.reduce((e,s)=>{var r,t;let l=null==s?void 0:null===(r=s.header)||void 0===r?void 0:r.trim();return l&&(e[l]=null!==(t=null==s?void 0:s.value)&&void 0!==t?t:""),e},{}):{},p=t&&"object"==typeof t?Object.entries(t).reduce((e,s)=>{let[r,t]=s;if(null==t||""===t)return e;if("scopes"===r){if(Array.isArray(t)){let s=t.filter(e=>null!=e&&""!==e);s.length>0&&(e[r]=s)}}else e[r]=t;return e},{}):void 0,g={};if(r&&"stdio"===L)try{let e=JSON.parse(r),s=e;if(e.mcpServers&&"object"==typeof e.mcpServers){let r=Object.keys(e.mcpServers);if(r.length>0){let t=r[0];s=e.mcpServers[t],c.server_name||(c.server_name=t.replace(/-/g,"_"))}}g={command:s.command,args:s.args,env:s.env},console.log("Parsed stdio config:",g)}catch(e){S.ZP.fromBackend("Invalid JSON in stdio configuration");return}let j={...c,...g,stdio_config:void 0,mcp_info:{server_name:c.server_name||c.url,description:c.description,mcp_server_cost_info:Object.keys(x).length>0?x:null},mcp_access_groups:m,alias:c.alias,allowed_tools:E.length>0?E:null,allow_all_keys:!!l,available_on_public_internet:!!i,static_headers:u};if(j.static_headers=u,c.auth_type&&ev.includes(c.auth_type)&&p&&Object.keys(p).length>0&&(j.credentials=p),console.log("Payload: ".concat(JSON.stringify(j))),null!=a){let e=await (0,_.createMCPServer)(a,j);S.ZP.success("MCP Server created successfully"),d.resetFields(),h({}),k([]),O([]),Z(!1),o(!1),n(e)}}catch(e){S.ZP.fromBackend("Error creating MCP Server: "+e)}finally{u(!1)}},Q=()=>{d.resetFields(),h({}),k([]),O([]),Z(!1),o(!1)};return(f.useEffect(()=>{if(!w&&j.server_name){let e=j.server_name.replace(/\s+/g,"_");d.setFieldsValue({alias:e}),y(s=>({...s,alias:e}))}},[j.server_name]),f.useEffect(()=>{i||y({})},[i]),(0,l.tY)(r))?(0,t.jsx)(g.Z,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:[(0,t.jsx)("img",{src:eg,alt:"MCP Logo",className:"w-8 h-8 object-contain",style:{height:"20px",width:"20px",marginRight:"8px",objectFit:"contain"}}),(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add New MCP Server"})]}),open:i,width:1e3,onCancel:Q,footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsxs)(P.Z,{form:d,onFinish:W,onValuesChange:(e,s)=>y(s),layout:"vertical",className:"space-y-6",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 gap-6",children:[(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["MCP Server Name",(0,t.jsx)(v.Z,{title:"Best practice: Use a descriptive name that indicates the server's purpose (e.g., 'GitHub_MCP', 'Email_Service'). Hyphens '-' are not allowed; use underscores '_' instead. Names must comply with SEP-986 and will be rejected if invalid (https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool-names).",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"server_name",rules:[{required:!1,message:"Please enter a server name"},{validator:(e,s)=>em(s)}],children:(0,t.jsx)(I.o,{placeholder:"e.g., GitHub_MCP, Zapier_MCP, etc.",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Alias",(0,t.jsx)(v.Z,{title:"A short, unique identifier for this server. Defaults to the server name with spaces replaced by underscores.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"alias",rules:[{required:!1},{validator:(e,s)=>s&&s.includes("-")?Promise.reject("Alias cannot contain '-' (hyphen). Please use '_' (underscore) instead."):Promise.resolve()}],children:(0,t.jsx)(I.o,{placeholder:"e.g., GitHub_MCP, Zapier_MCP, etc.",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500",onChange:()=>Z(!0)})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Description"}),name:"description",rules:[{required:!1,message:"Please enter a server description!!!!!!!!!"}],children:(0,t.jsx)(I.o,{placeholder:"Brief description of what this server does",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Transport Type"}),name:"transport",rules:[{required:!0,message:"Please select a transport type"}],children:(0,t.jsxs)(p.default,{placeholder:"Select transport",className:"rounded-lg",size:"large",onChange:e=>{z(e),"stdio"===e?d.setFieldsValue({url:void 0,auth_type:void 0,credentials:void 0}):d.setFieldsValue({command:void 0,args:void 0,env:void 0})},value:L,children:[(0,t.jsx)(p.default.Option,{value:"http",children:"HTTP"}),(0,t.jsx)(p.default.Option,{value:"sse",children:"Server-Sent Events (SSE)"}),(0,t.jsx)(p.default.Option,{value:"stdio",children:"Standard Input/Output (stdio)"})]})}),"stdio"!==L&&(0,t.jsx)(P.Z.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"MCP Server URL"}),name:"url",rules:[{required:!0,message:"Please enter a server URL"},{validator:(e,s)=>ed(s)}],children:(0,t.jsx)(A.default,{placeholder:"https://your-mcp-server.com",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),"stdio"!==L&&(0,t.jsx)(P.Z.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Authentication"}),name:"auth_type",rules:[{required:!0,message:"Please select an auth type"}],children:(0,t.jsxs)(p.default,{placeholder:"Select auth type",className:"rounded-lg",size:"large",children:[(0,t.jsx)(p.default.Option,{value:"none",children:"None"}),(0,t.jsx)(p.default.Option,{value:"api_key",children:"API Key"}),(0,t.jsx)(p.default.Option,{value:"bearer_token",children:"Bearer Token"}),(0,t.jsx)(p.default.Option,{value:"basic",children:"Basic Auth"}),(0,t.jsx)(p.default.Option,{value:"oauth2",children:"OAuth"})]})}),"stdio"!==L&&D&&(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Authentication Value",(0,t.jsx)(v.Z,{title:"Token, password, or header value to send with each request for the selected auth type.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:["credentials","auth_value"],rules:[{required:!0,message:"Please enter the authentication value"}],children:(0,t.jsx)(I.o,{type:"password",placeholder:"Enter token or secret",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),"stdio"!==L&&K&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["OAuth Client ID (optional)",(0,t.jsx)(v.Z,{title:"Provide only if your MCP server cannot handle dynamic client registration.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:["credentials","client_id"],children:(0,t.jsx)(I.o,{type:"password",placeholder:"Enter OAuth client ID",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["OAuth Client Secret (optional)",(0,t.jsx)(v.Z,{title:"Provide only if your MCP server cannot handle dynamic client registration.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:["credentials","client_secret"],children:(0,t.jsx)(I.o,{type:"password",placeholder:"Enter OAuth client secret",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["OAuth Scopes (optional)",(0,t.jsx)(v.Z,{title:"Optional scopes requested during token exchange. Separate multiple scopes with enter or commas.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:["credentials","scopes"],children:(0,t.jsx)(p.default,{mode:"tags",tokenSeparators:[","],placeholder:"Add scopes",className:"rounded-lg",size:"large"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Authorization URL Override (optional)",(0,t.jsx)(v.Z,{title:"Optional override for the authorization endpoint.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"authorization_url",children:(0,t.jsx)(I.o,{placeholder:"https://example.com/oauth/authorize",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Token URL Override (optional)",(0,t.jsx)(v.Z,{title:"Optional override for the token endpoint.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"token_url",children:(0,t.jsx)(I.o,{placeholder:"https://example.com/oauth/token",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Registration URL Override (optional)",(0,t.jsx)(v.Z,{title:"Optional orverride for the dynamic client registration endpoint.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"registration_url",children:(0,t.jsx)(I.o,{placeholder:"https://example.com/oauth/register",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsxs)("div",{className:"rounded-lg border border-dashed border-gray-300 p-4 space-y-2",children:[(0,t.jsx)("p",{className:"text-sm text-gray-600",children:"Use OAuth to fetch a fresh access token and temporarily save it in the session as the authentication value."}),(0,t.jsx)(I.z,{variant:"secondary",onClick:H,disabled:"authorizing"===J||"exchanging"===J,children:"authorizing"===J?"Waiting for authorization...":"exchanging"===J?"Exchanging authorization code...":"Authorize & Fetch Token"}),G&&(0,t.jsx)("p",{className:"text-sm text-red-500",children:G}),"success"===J&&(null==Y?void 0:Y.access_token)&&(0,t.jsxs)("p",{className:"text-sm text-green-600",children:["Token fetched. Expires in ",null!==(s=Y.expires_in)&&void 0!==s?s:"?"," seconds."]})]})]}),(0,t.jsx)(ee,{isVisible:"stdio"===L})]}),(0,t.jsx)("div",{className:"mt-8",children:(0,t.jsx)(en,{availableAccessGroups:c,mcpServer:null,searchValue:F,setSearchValue:q,getAccessGroupOptions:()=>{let e=c.map(e=>({value:e,label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:e})]})}));return F&&!c.some(e=>e.toLowerCase().includes(F.toLowerCase()))&&e.push({value:F,label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:F}),(0,t.jsx)("span",{className:"text-gray-400 text-xs ml-1",children:"create new group"})]})}),e}})}),(0,t.jsx)("div",{className:"mt-8 pt-6 border-t border-gray-200",children:(0,t.jsx)($,{accessToken:a,oauthAccessToken:R,formValues:j,onToolsLoaded:k})}),(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(X,{accessToken:a,oauthAccessToken:R,formValues:j,allowedTools:E,existingAllowedTools:null,onAllowedToolsChange:O})}),(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(B,{value:x,onChange:h,tools:C.filter(e=>E.includes(e.name)),disabled:!1})}),(0,t.jsxs)("div",{className:"flex items-center justify-end space-x-3 pt-6 border-t border-gray-100",children:[(0,t.jsx)(I.z,{variant:"secondary",onClick:Q,children:"Cancel"}),(0,t.jsx)(I.z,{variant:"primary",loading:m,children:m?"Creating...":"Add MCP Server"})]})]})})}):null},eb=r(5945),eN=r(64935),e_=r(30401),ew=r(78867),eZ=r(11239),eC=r(54001),eS=r(96137),ek=r(96362),eP=r(80221),eA=r(29202),eT=r(59872);let{Title:eI,Text:eM}=h.default,{Panel:eE}=F.default,eO=e=>{let{icon:s,title:r,description:l,children:a,serverName:n,accessGroups:i=["dev-group"]}=e,[o,c]=(0,f.useState)(!1),d=()=>{let e={"x-litellm-api-key":"Bearer YOUR_LITELLM_API_KEY"};if(o&&n){let s=[n.replace(/\s+/g,"_"),...i].join(",");e["x-mcp-servers"]=s}return e};return(0,t.jsxs)(eb.Z,{className:"border border-gray-200",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-3",children:[(0,t.jsx)("span",{className:"p-2 rounded-lg bg-gray-50",children:s}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eI,{level:5,className:"mb-0",children:r}),(0,t.jsx)(eM,{className:"text-gray-600",children:l})]})]}),n&&("Implementation Example"===r||"Configuration"===r)&&(0,t.jsxs)(P.Z.Item,{className:"mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,t.jsx)(es.Z,{size:"small",checked:o,onChange:c}),(0,t.jsxs)(eM,{className:"text-sm",children:["Limit tools to specific MCP servers or MCP groups by passing the ",(0,t.jsx)("code",{children:"x-mcp-servers"})," header"]})]}),o&&(0,t.jsx)(K.Z,{className:"mt-2",type:"info",showIcon:!0,message:"Two Options",description:(0,t.jsxs)("div",{children:[(0,t.jsxs)("p",{children:[(0,t.jsx)("strong",{children:"Option 1:"})," Get a specific server: ",(0,t.jsxs)("code",{children:['"',n.replace(/\s+/g,"_"),'"']})]}),(0,t.jsxs)("p",{children:[(0,t.jsx)("strong",{children:"Option 2:"})," Get a group of MCPs: ",(0,t.jsx)("code",{children:'"dev-group"'})]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-gray-600",children:["You can also mix both: ",(0,t.jsx)("code",{children:'"Server1,dev-group"'})]})]})})]}),f.Children.map(a,e=>{if(f.isValidElement(e)&&e.props.hasOwnProperty("code")&&e.props.hasOwnProperty("copyKey")){let s=e.props.code;if(s&&s.includes('"headers":'))return f.cloneElement(e,{code:s.replace(/"headers":\s*{[^}]*}/,'"headers": '.concat(JSON.stringify(d(),null,8)))})}return e})]})};var eL=e=>{let{currentServerAccessGroups:s=[]}=e,r=(0,_.getProxyBaseUrl)(),[l,a]=(0,f.useState)({}),[n,h]=(0,f.useState)({openai:[],litellm:[],cursor:[],http:[]}),[p]=(0,f.useState)("Zapier_MCP"),g=async(e,s)=>{await (0,eT.vQ)(e)&&(a(e=>({...e,[s]:!0})),setTimeout(()=>{a(e=>({...e,[s]:!1}))},2e3))},j=e=>{let{code:s,copyKey:r,title:a,className:n=""}=e;return(0,t.jsxs)("div",{className:"relative group",children:[a&&(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,t.jsx)(eN.Z,{size:16,className:"text-blue-600"}),(0,t.jsx)(eM,{strong:!0,className:"text-gray-700",children:a})]}),(0,t.jsxs)(eb.Z,{className:"bg-gray-50 border border-gray-200 relative ".concat(n),children:[(0,t.jsx)(H.ZP,{type:"text",size:"small",icon:l[r]?(0,t.jsx)(e_.Z,{size:12}):(0,t.jsx)(ew.Z,{size:12}),onClick:()=>g(s,r),className:"absolute top-2 right-2 z-10 transition-all duration-200 ".concat(l[r]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100")}),(0,t.jsx)("pre",{className:"text-sm overflow-x-auto pr-10 text-gray-800 font-mono leading-relaxed",children:s})]})]})},v=e=>{let{step:s,title:r,children:l}=e;return(0,t.jsxs)("div",{className:"flex gap-4",children:[(0,t.jsx)("div",{className:"flex-shrink-0",children:(0,t.jsx)("div",{className:"w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold",children:s})}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(eM,{strong:!0,className:"text-gray-800 block mb-2",children:r}),l]})]})};return(0,t.jsx)("div",{children:(0,t.jsxs)(er.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(x.Z,{className:"text-3xl font-bold text-gray-900 mb-3",children:"Connect to your MCP client"}),(0,t.jsx)(u.Z,{className:"text-lg text-gray-600",children:"Use tools directly from any MCP client with LiteLLM MCP. Enable your AI assistant to perform real-world tasks through a simple, secure connection."})]}),(0,t.jsxs)(o.Z,{className:"w-full",children:[(0,t.jsx)(c.Z,{className:"flex justify-start mt-8 mb-6",children:(0,t.jsxs)("div",{className:"flex bg-gray-100 p-1 rounded-lg",children:[(0,t.jsx)(i.Z,{className:"px-6 py-3 rounded-md transition-all duration-200",children:(0,t.jsxs)("span",{className:"flex items-center gap-2 font-medium",children:[(0,t.jsx)(eN.Z,{size:18}),"OpenAI API"]})}),(0,t.jsx)(i.Z,{className:"px-6 py-3 rounded-md transition-all duration-200",children:(0,t.jsxs)("span",{className:"flex items-center gap-2 font-medium",children:[(0,t.jsx)(eZ.Z,{size:18}),"LiteLLM Proxy"]})}),(0,t.jsx)(i.Z,{className:"px-6 py-3 rounded-md transition-all duration-200",children:(0,t.jsxs)("span",{className:"flex items-center gap-2 font-medium",children:[(0,t.jsx)(eP.Z,{size:18}),"Cursor"]})}),(0,t.jsx)(i.Z,{className:"px-6 py-3 rounded-md transition-all duration-200",children:(0,t.jsxs)("span",{className:"flex items-center gap-2 font-medium",children:[(0,t.jsx)(eA.Z,{size:18}),"Streamable HTTP"]})})]})}),(0,t.jsxs)(m.Z,{children:[(0,t.jsx)(d.Z,{className:"mt-6",children:(0,t.jsx)(()=>(0,t.jsxs)(er.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsxs)("div",{className:"bg-gradient-to-r from-blue-50 to-indigo-50 p-6 rounded-lg border border-blue-100",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-3",children:[(0,t.jsx)(eN.Z,{className:"text-blue-600",size:24}),(0,t.jsx)(eI,{level:4,className:"mb-0 text-blue-900",children:"OpenAI Responses API Integration"})]}),(0,t.jsx)(eM,{className:"text-blue-700",children:"Connect OpenAI Responses API to your LiteLLM MCP server for seamless tool integration"})]}),(0,t.jsxs)(er.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsx)(eO,{icon:(0,t.jsx)(eC.Z,{className:"text-blue-600",size:16}),title:"API Key Setup",description:"Configure your OpenAI API key for authentication",children:(0,t.jsxs)(er.Z,{direction:"vertical",size:"middle",className:"w-full",children:[(0,t.jsx)("div",{children:(0,t.jsxs)(eM,{children:["Get your API key from the"," ",(0,t.jsxs)("a",{href:"https://platform.openai.com/api-keys",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-700 inline-flex items-center gap-1",children:["OpenAI platform ",(0,t.jsx)(ek.Z,{size:12})]})]})}),(0,t.jsx)(j,{title:"Environment Variable",code:'export OPENAI_API_KEY="sk-..."',copyKey:"openai-env"})]})}),(0,t.jsx)(eO,{icon:(0,t.jsx)(eS.Z,{className:"text-blue-600",size:16}),title:"MCP Server Information",description:"Connection details for your LiteLLM MCP server",children:(0,t.jsx)(j,{title:"Server URL",code:"".concat(r,"/mcp"),copyKey:"openai-server-url"})}),(0,t.jsx)(eO,{icon:(0,t.jsx)(eN.Z,{className:"text-blue-600",size:16}),title:"Implementation Example",description:"Complete cURL example for using the Responses API",serverName:"Zapier Gmail",accessGroups:["dev-group"],children:(0,t.jsx)(j,{code:'curl --location \'https://api.openai.com/v1/responses\' \\\n--header \'Content-Type: application/json\' \\\n--header "Authorization: Bearer $OPENAI_API_KEY" \\\n--data \'{\n "model": "gpt-4.1",\n "tools": [\n {\n "type": "mcp",\n "server_label": "litellm",\n "server_url": "'.concat(r,'/mcp",\n "require_approval": "never",\n "headers": {\n "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",\n "x-mcp-servers": "Zapier_MCP,dev-group"\n }\n }\n ],\n "input": "Run available tools",\n "tool_choice": "required"\n}\''),copyKey:"openai-curl",className:"text-xs"})})]})]}),{})}),(0,t.jsx)(d.Z,{className:"mt-6",children:(0,t.jsx)(()=>(0,t.jsxs)(er.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsxs)("div",{className:"bg-gradient-to-r from-emerald-50 to-green-50 p-6 rounded-lg border border-emerald-100",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-3",children:[(0,t.jsx)(eZ.Z,{className:"text-emerald-600",size:24}),(0,t.jsx)(eI,{level:4,className:"mb-0 text-emerald-900",children:"LiteLLM Proxy API Integration"})]}),(0,t.jsx)(eM,{className:"text-emerald-700",children:"Connect to LiteLLM Proxy Responses API for seamless tool integration with multiple model providers"})]}),(0,t.jsxs)(er.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsx)(eO,{icon:(0,t.jsx)(eC.Z,{className:"text-emerald-600",size:16}),title:"Virtual Key Setup",description:"Configure your LiteLLM Proxy Virtual Key for authentication",children:(0,t.jsxs)(er.Z,{direction:"vertical",size:"middle",className:"w-full",children:[(0,t.jsx)("div",{children:(0,t.jsx)(eM,{children:"Get your Virtual Key from your LiteLLM Proxy dashboard or contact your administrator"})}),(0,t.jsx)(j,{title:"Environment Variable",code:'export LITELLM_API_KEY="sk-..."',copyKey:"litellm-env"})]})}),(0,t.jsx)(eO,{icon:(0,t.jsx)(eS.Z,{className:"text-emerald-600",size:16}),title:"MCP Server Information",description:"Connection details for your LiteLLM MCP server",children:(0,t.jsx)(j,{title:"Server URL",code:"".concat(r,"/mcp"),copyKey:"litellm-server-url"})}),(0,t.jsx)(eO,{icon:(0,t.jsx)(eN.Z,{className:"text-emerald-600",size:16}),title:"Implementation Example",description:"Complete cURL example for using the LiteLLM Proxy Responses API",serverName:p,accessGroups:["dev-group"],children:(0,t.jsx)(j,{code:"curl --location '".concat(r,'/v1/responses\' \\\n--header \'Content-Type: application/json\' \\\n--header "Authorization: Bearer $LITELLM_VIRTUAL_KEY" \\\n--data \'{\n "model": "gpt-4",\n "tools": [\n {\n "type": "mcp",\n "server_label": "litellm",\n "server_url": "').concat(r,'/mcp",\n "require_approval": "never",\n "headers": {\n "x-litellm-api-key": "Bearer YOUR_LITELLM_VIRTUAL_KEY",\n "x-mcp-servers": "Zapier_MCP,dev-group"\n }\n }\n ],\n "input": "Run available tools",\n "tool_choice": "required"\n}\''),copyKey:"litellm-curl",className:"text-xs"})})]})]}),{})}),(0,t.jsx)(d.Z,{className:"mt-6",children:(0,t.jsx)(()=>(0,t.jsxs)(er.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsxs)("div",{className:"bg-gradient-to-r from-purple-50 to-blue-50 p-6 rounded-lg border border-purple-100",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-3",children:[(0,t.jsx)(eP.Z,{className:"text-purple-600",size:24}),(0,t.jsx)(eI,{level:4,className:"mb-0 text-purple-900",children:"Cursor IDE Integration"})]}),(0,t.jsx)(eM,{className:"text-purple-700",children:"Use tools directly from Cursor IDE with LiteLLM MCP. Enable your AI assistant to perform real-world tasks without leaving your coding environment."})]}),(0,t.jsxs)(eb.Z,{className:"border border-gray-200",children:[(0,t.jsx)(eI,{level:5,className:"mb-4 text-gray-800",children:"Setup Instructions"}),(0,t.jsxs)(er.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsx)(v,{step:1,title:"Open Cursor Settings",children:(0,t.jsxs)(eM,{className:"text-gray-600",children:["Use the keyboard shortcut ",(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"⇧+⌘+J"})," (Mac) or"," ",(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"Ctrl+Shift+J"})," (Windows/Linux)"]})}),(0,t.jsx)(v,{step:2,title:"Navigate to MCP Tools",children:(0,t.jsx)(eM,{className:"text-gray-600",children:'Go to the "MCP Tools" tab and click "New MCP Server"'})}),(0,t.jsxs)(v,{step:3,title:"Add Configuration",children:[(0,t.jsxs)(eM,{className:"text-gray-600 mb-3",children:["Copy the JSON configuration below and paste it into Cursor, then save with"," ",(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"Cmd+S"})," or"," ",(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"Ctrl+S"})]}),(0,t.jsx)(eO,{icon:(0,t.jsx)(eN.Z,{className:"text-purple-600",size:16}),title:"Configuration",description:"Cursor MCP configuration",serverName:"Zapier Gmail",accessGroups:["dev-group"],children:(0,t.jsx)(j,{code:'{\n "mcpServers": {\n "Zapier_MCP": {\n "url": "'.concat(r,'/mcp",\n "headers": {\n "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",\n "x-mcp-servers": "Zapier_MCP,dev-group"\n }\n }\n }\n}'),copyKey:"cursor-config",className:"text-xs"})})]})]})]})]}),{})}),(0,t.jsx)(d.Z,{className:"mt-6",children:(0,t.jsx)(()=>(0,t.jsxs)(er.Z,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsxs)("div",{className:"bg-gradient-to-r from-green-50 to-teal-50 p-6 rounded-lg border border-green-100",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-3",children:[(0,t.jsx)(eA.Z,{className:"text-green-600",size:24}),(0,t.jsx)(eI,{level:4,className:"mb-0 text-green-900",children:"Streamable HTTP Transport"})]}),(0,t.jsx)(eM,{className:"text-green-700",children:"Connect to LiteLLM MCP using HTTP transport. Compatible with any MCP client that supports HTTP streaming."})]}),(0,t.jsx)(eO,{icon:(0,t.jsx)(eA.Z,{className:"text-green-600",size:16}),title:"Universal MCP Connection",description:"Use this URL with any MCP client that supports HTTP transport",children:(0,t.jsxs)(er.Z,{direction:"vertical",size:"middle",className:"w-full",children:[(0,t.jsx)("div",{children:(0,t.jsx)(eM,{children:"Each MCP client supports different transports. Refer to your client documentation to determine the appropriate transport method."})}),(0,t.jsx)(j,{title:"Server URL",code:"".concat(r,"/mcp"),copyKey:"http-server-url"}),(0,t.jsx)(j,{title:"Headers Configuration",code:JSON.stringify({"x-litellm-api-key":"Bearer YOUR_LITELLM_API_KEY"},null,2),copyKey:"http-headers"}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(H.ZP,{type:"link",className:"p-0 h-auto text-blue-600 hover:text-blue-700",href:"https://modelcontextprotocol.io/docs/concepts/transports",icon:(0,t.jsx)(ek.Z,{size:14}),children:"Learn more about MCP transports"})})]})})]}),{})})]})]})]})})},ez=r(58927),eF=r(53410),eq=r(74998);let eR=(e,s,r,l,a)=>[{accessorKey:"server_id",header:"Server ID",cell:e=>{let{row:r}=e;return(0,t.jsxs)("button",{onClick:()=>s(r.original.server_id),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 max-w-[15ch]",children:[r.original.server_id.slice(0,7),"..."]})}},{accessorKey:"server_name",header:"Name"},{accessorKey:"alias",header:"Alias"},{id:"url",header:"URL",cell:e=>{let{row:s}=e,{maskedUrl:r}=ec(s.original.url);return(0,t.jsx)("span",{className:"font-mono text-sm",children:r})}},{accessorKey:"transport",header:"Transport",cell:e=>{let{getValue:s}=e;return(0,t.jsx)("span",{children:(s()||"http").toUpperCase()})}},{accessorKey:"auth_type",header:"Auth Type",cell:e=>{let{getValue:s}=e;return(0,t.jsx)("span",{children:s()||"none"})}},{id:"health_status",header:"Health Status",cell:e=>{let{row:s}=e,r=s.original,l=r.status||"unknown",n=r.last_health_check,i=r.health_check_error;if(a)return(0,t.jsxs)("div",{className:"flex items-center text-gray-500",children:[(0,t.jsxs)("svg",{className:"animate-spin h-4 w-4 mr-1",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[(0,t.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,t.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"})]}),(0,t.jsx)("span",{className:"text-xs",children:"Loading..."})]});let o=(0,t.jsxs)("div",{className:"max-w-xs",children:[(0,t.jsxs)("div",{className:"font-semibold mb-1",children:["Health Status: ",l]}),n&&(0,t.jsxs)("div",{className:"text-xs mb-1",children:["Last Check: ",new Date(n).toLocaleString()]}),i&&(0,t.jsxs)("div",{className:"text-xs",children:[(0,t.jsx)("div",{className:"font-medium text-red-400 mb-1",children:"Error:"}),(0,t.jsx)("div",{className:"break-words",children:i})]}),!n&&!i&&(0,t.jsx)("div",{className:"text-xs text-gray-400",children:"No health check data available"})]});return(0,t.jsx)(v.Z,{title:o,placement:"top",children:(0,t.jsxs)("button",{className:"font-mono text-xs font-normal px-2 py-0.5 text-left w-full truncate whitespace-nowrap cursor-pointer max-w-[10ch] ".concat((e=>{switch(e){case"healthy":return"text-green-500 bg-green-50 hover:bg-green-100";case"unhealthy":return"text-red-500 bg-red-50 hover:bg-red-100";default:return"text-gray-500 bg-gray-50 hover:bg-gray-100"}})(l)),children:[(0,t.jsx)("span",{className:"mr-1",children:"●"}),l.charAt(0).toUpperCase()+l.slice(1)]})})}},{id:"mcp_access_groups",header:"Access Groups",cell:e=>{let{row:s}=e,r=s.original.mcp_access_groups;if(Array.isArray(r)&&r.length>0&&"string"==typeof r[0]){let e=r.join(", ");return(0,t.jsx)(v.Z,{title:e,children:(0,t.jsx)("span",{className:"max-w-[200px] truncate block",children:e.length>30?"".concat(e.slice(0,30),"..."):e})})}return(0,t.jsx)("span",{className:"text-gray-400 italic",children:"None"})}},{id:"available_on_public_internet",header:"Network Access",cell:e=>{let{row:s}=e;return s.original.available_on_public_internet?(0,t.jsx)("span",{className:"px-2 py-0.5 bg-green-50 text-green-700 rounded text-xs font-medium",children:"Public"}):(0,t.jsx)("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-xs font-medium",children:"Internal"})}},{header:"Created At",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,r=s.original;return(0,t.jsx)("span",{className:"text-xs",children:r.created_at?new Date(r.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,r=s.original;return(0,t.jsx)("span",{className:"text-xs",children:r.updated_at?new Date(r.updated_at).toLocaleDateString():"-"})}},{id:"actions",header:"Actions",cell:e=>{let{row:s}=e;return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(v.Z,{title:"Edit MCP Server",children:(0,t.jsx)(ez.J,{icon:eF.Z,size:"sm",onClick:()=>r(s.original.server_id),className:"cursor-pointer hover:text-blue-600"})}),(0,t.jsx)(v.Z,{title:"Delete MCP Server",children:(0,t.jsx)(ez.J,{icon:eq.Z,size:"sm",onClick:()=>l(s.original.server_id),className:"cursor-pointer hover:text-red-600"})})]})}}];var eU=r(10900),eV=r(82376),eB=r(71437),eD=r(12514),eK=r(67101),eH=r(47323),eJ=r(49566);let eG=[M.API_KEY,M.BEARER_TOKEN,M.BASIC],eY=[...eG,M.OAUTH2],eW="litellm-mcp-oauth-edit-state";var e$=e=>{var s;let{mcpServer:r,accessToken:l,onCancel:a,onSuccess:u,availableAccessGroups:x}=e,[h]=P.Z.useForm(),[g,j]=(0,f.useState)({}),[y,b]=(0,f.useState)([]),[N,w]=(0,f.useState)(!1),[Z,C]=(0,f.useState)(""),[k,A]=(0,f.useState)(!1),[I,E]=(0,f.useState)([]),[O,L]=(0,f.useState)(null),z=P.Z.useWatch("auth_type",h),F=!!z&&eG.includes(z),q=z===M.OAUTH2,[R,U]=(0,f.useState)(null),{startOAuthFlow:V,status:D,error:K,tokenResponse:J}=ep({accessToken:l,getCredentials:()=>h.getFieldValue("credentials"),getTemporaryPayload:()=>{let e=h.getFieldsValue(!0),s=e.url||r.url,t=e.transport||r.transport;if(!s||!t)return null;let l=Array.isArray(e.static_headers)?e.static_headers.reduce((e,s)=>{var r,t;let l=null==s?void 0:null===(r=s.header)||void 0===r?void 0:r.trim();return l&&(e[l]=null!==(t=null==s?void 0:s.value)&&void 0!==t?t:""),e},{}):{};return{server_id:r.server_id,server_name:e.server_name||r.server_name||r.alias,alias:e.alias||r.alias,description:e.description||r.description,url:s,transport:t,auth_type:M.OAUTH2,credentials:e.credentials,mcp_access_groups:e.mcp_access_groups||r.mcp_access_groups,static_headers:l,command:e.command,args:e.args,env:e.env}},onTokenReceived:e=>{var s;U(null!==(s=null==e?void 0:e.access_token)&&void 0!==s?s:null)},onBeforeRedirect:()=>{try{let e=h.getFieldsValue(!0);window.sessionStorage.setItem(eW,JSON.stringify({serverId:r.server_id,formValues:e,costConfig:g,allowedTools:I,searchValue:Z,aliasManuallyEdited:k}))}catch(e){console.warn("Failed to persist MCP edit state",e)}}}),G=f.useMemo(()=>r.static_headers?Object.entries(r.static_headers).map(e=>{let[s,r]=e;return{header:s,value:null!=r?String(r):""}}):[],[r.static_headers]),Y=f.useMemo(()=>({...r,static_headers:G}),[r,G]);(0,f.useEffect)(()=>{var e;(null===(e=r.mcp_info)||void 0===e?void 0:e.mcp_server_cost_info)&&j(r.mcp_info.mcp_server_cost_info)},[r]),(0,f.useEffect)(()=>{r.allowed_tools&&E(r.allowed_tools)},[r]),(0,f.useEffect)(()=>{let e=window.sessionStorage.getItem(eW);if(e)try{let s=JSON.parse(e);if(!s||s.serverId!==r.server_id)return;s.formValues&&L({...r,...s.formValues}),s.costConfig&&j(s.costConfig),s.allowedTools&&E(s.allowedTools),s.searchValue&&C(s.searchValue),"boolean"==typeof s.aliasManuallyEdited&&A(s.aliasManuallyEdited)}catch(e){console.error("Failed to restore MCP edit state",e)}finally{window.sessionStorage.removeItem(eW)}},[h,r]),(0,f.useEffect)(()=>{if(!O)return;let e=O.transport||r.transport;if(e&&e!==h.getFieldValue("transport")){h.setFieldsValue({transport:e});return}h.setFieldsValue(O),L(null)},[O,h,r.transport]),(0,f.useEffect)(()=>{if(r.mcp_access_groups){let e=r.mcp_access_groups.map(e=>"string"==typeof e?e:e.name||String(e));h.setFieldValue("mcp_access_groups",e)}},[r]),(0,f.useEffect)(()=>{W()},[r,l,R]);let W=async()=>{if(l&&r.url&&(r.auth_type!==M.OAUTH2||R)){w(!0);try{let e={server_id:r.server_id,server_name:r.server_name,url:r.url,transport:r.transport,auth_type:r.auth_type,mcp_info:r.mcp_info,authorization_url:r.authorization_url,token_url:r.token_url,registration_url:r.registration_url},s=await (0,_.testMCPToolsListRequest)(l,e,R);s.tools&&!s.error?b(s.tools):(console.error("Failed to fetch tools:",s.message),b([]))}catch(e){console.error("Tools fetch error:",e),b([])}finally{w(!1)}}},$=async e=>{if(l)try{let{static_headers:s,credentials:t,allow_all_keys:a,available_on_public_internet:n,...i}=e,o=(i.mcp_access_groups||[]).map(e=>"string"==typeof e?e:e.name||String(e)),c=Array.isArray(s)?s.reduce((e,s)=>{var r,t;let l=null==s?void 0:null===(r=s.header)||void 0===r?void 0:r.trim();return l&&(e[l]=null!==(t=null==s?void 0:s.value)&&void 0!==t?t:""),e},{}):{},d=t&&"object"==typeof t?Object.entries(t).reduce((e,s)=>{let[r,t]=s;if(null==t||""===t)return e;if("scopes"===r){if(Array.isArray(t)){let s=t.filter(e=>null!=e&&""!==e);s.length>0&&(e[r]=s)}}else e[r]=t;return e},{}):void 0,m={...i,server_id:r.server_id,mcp_info:{server_name:i.server_name||i.url,description:i.description,mcp_server_cost_info:Object.keys(g).length>0?g:null},mcp_access_groups:o,alias:i.alias,extra_headers:i.extra_headers||[],allowed_tools:I.length>0?I:null,disallowed_tools:i.disallowed_tools||[],static_headers:c,allow_all_keys:!!(null!=a?a:r.allow_all_keys),available_on_public_internet:!!(null!=n?n:r.available_on_public_internet)};i.auth_type&&eY.includes(i.auth_type)&&d&&Object.keys(d).length>0&&(m.credentials=d);let x=await (0,_.updateMCPServer)(l,m);S.ZP.success("MCP Server updated successfully"),u(x)}catch(e){S.ZP.fromBackend("Failed to update MCP Server"+((null==e?void 0:e.message)?": ".concat(e.message):""))}};return(0,t.jsxs)(o.Z,{children:[(0,t.jsxs)(c.Z,{className:"grid w-full grid-cols-2",children:[(0,t.jsx)(i.Z,{children:"Server Configuration"}),(0,t.jsx)(i.Z,{children:"Cost Configuration"})]}),(0,t.jsxs)(m.Z,{className:"mt-6",children:[(0,t.jsx)(d.Z,{children:(0,t.jsxs)(P.Z,{form:h,onFinish:$,initialValues:Y,layout:"vertical",children:[(0,t.jsx)(P.Z.Item,{label:"MCP Server Name",name:"server_name",rules:[{validator:(e,s)=>em(s)}],children:(0,t.jsx)(eJ.Z,{})}),(0,t.jsx)(P.Z.Item,{label:"Alias",name:"alias",rules:[{validator:(e,s)=>em(s)}],children:(0,t.jsx)(eJ.Z,{onChange:()=>A(!0)})}),(0,t.jsx)(P.Z.Item,{label:"Description",name:"description",children:(0,t.jsx)(eJ.Z,{})}),(0,t.jsx)(P.Z.Item,{label:"MCP Server URL",name:"url",rules:[{required:!0,message:"Please enter a server URL"},{validator:(e,s)=>ed(s)}],children:(0,t.jsx)(eJ.Z,{})}),(0,t.jsx)(P.Z.Item,{label:"Transport Type",name:"transport",rules:[{required:!0}],children:(0,t.jsxs)(p.default,{children:[(0,t.jsx)(p.default.Option,{value:"sse",children:"Server-Sent Events (SSE)"}),(0,t.jsx)(p.default.Option,{value:"http",children:"HTTP"})]})}),(0,t.jsx)(P.Z.Item,{label:"Authentication",name:"auth_type",rules:[{required:!0}],children:(0,t.jsxs)(p.default,{children:[(0,t.jsx)(p.default.Option,{value:"none",children:"None"}),(0,t.jsx)(p.default.Option,{value:"api_key",children:"API Key"}),(0,t.jsx)(p.default.Option,{value:"bearer_token",children:"Bearer Token"}),(0,t.jsx)(p.default.Option,{value:"basic",children:"Basic Auth"}),(0,t.jsx)(p.default.Option,{value:"oauth2",children:"OAuth"})]})}),F&&(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Authentication Value",(0,t.jsx)(v.Z,{title:"Token, password, or header value to send with each request for the selected auth type.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:["credentials","auth_value"],rules:[{validator:(e,s)=>s&&"string"==typeof s&&""===s.trim()?Promise.reject(Error("Authentication value cannot be empty")):Promise.resolve()}],children:(0,t.jsx)(eJ.Z,{type:"password",placeholder:"Enter token or secret (leave blank to keep existing)",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),q&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["OAuth Client ID (optional)",(0,t.jsx)(v.Z,{title:"Provide only if your MCP server cannot handle dynamic client registration.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:["credentials","client_id"],children:(0,t.jsx)(eJ.Z,{type:"password",placeholder:"Enter OAuth client ID (leave blank to keep existing)",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["OAuth Client Secret (optional)",(0,t.jsx)(v.Z,{title:"Provide only if your MCP server cannot handle dynamic client registration.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:["credentials","client_secret"],children:(0,t.jsx)(eJ.Z,{type:"password",placeholder:"Enter OAuth client secret (leave blank to keep existing)",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["OAuth Scopes (optional)",(0,t.jsx)(v.Z,{title:"Add scopes to override the default scope list used for this MCP server.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:["credentials","scopes"],children:(0,t.jsx)(p.default,{mode:"tags",tokenSeparators:[","],placeholder:"Add scopes",className:"rounded-lg",size:"large"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Authorization URL Override (optional)",(0,t.jsx)(v.Z,{title:"Optional override for the authorization endpoint.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"authorization_url",children:(0,t.jsx)(eJ.Z,{placeholder:"https://example.com/oauth/authorize",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Token URL Override (optional)",(0,t.jsx)(v.Z,{title:"Optional override for the token endpoint.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"token_url",children:(0,t.jsx)(eJ.Z,{placeholder:"https://example.com/oauth/token",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Registration URL Override (optional)",(0,t.jsx)(v.Z,{title:"Optional override for the dynamic client registration endpoint.",children:(0,t.jsx)(T.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"registration_url",children:(0,t.jsx)(eJ.Z,{placeholder:"https://example.com/oauth/register",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsxs)("div",{className:"rounded-lg border border-dashed border-gray-300 p-4 space-y-2",children:[(0,t.jsx)("p",{className:"text-sm text-gray-600",children:"Use OAuth to fetch a fresh access token and temporarily save it in the session as the authentication value."}),(0,t.jsx)(n.Z,{variant:"secondary",onClick:V,disabled:"authorizing"===D||"exchanging"===D,children:"authorizing"===D?"Waiting for authorization...":"exchanging"===D?"Exchanging authorization code...":"Authorize & Fetch Token"}),K&&(0,t.jsx)("p",{className:"text-sm text-red-500",children:K}),"success"===D&&(null==J?void 0:J.access_token)&&(0,t.jsxs)("p",{className:"text-sm text-green-600",children:["Token fetched. Expires in ",null!==(s=J.expires_in)&&void 0!==s?s:"?"," seconds."]})]})]}),(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(en,{availableAccessGroups:x,mcpServer:r,searchValue:Z,setSearchValue:C,getAccessGroupOptions:()=>{let e=x.map(e=>({value:e,label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:e})]})}));return Z&&!x.some(e=>e.toLowerCase().includes(Z.toLowerCase()))&&e.push({value:Z,label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:Z}),(0,t.jsx)("span",{className:"text-gray-400 text-xs ml-1",children:"create new group"})]})}),e}})}),(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(X,{accessToken:l,oauthAccessToken:R,formValues:{server_id:r.server_id,server_name:r.server_name,url:r.url,transport:r.transport,auth_type:r.auth_type,mcp_info:r.mcp_info},allowedTools:I,existingAllowedTools:r.allowed_tools||null,onAllowedToolsChange:E})}),(0,t.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,t.jsx)(H.ZP,{onClick:a,children:"Cancel"}),(0,t.jsx)(n.Z,{type:"submit",children:"Save Changes"})]})]})}),(0,t.jsx)(d.Z,{children:(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)(B,{value:g,onChange:j,tools:y,disabled:N}),(0,t.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,t.jsx)(H.ZP,{onClick:a,children:"Cancel"}),(0,t.jsx)(n.Z,{onClick:()=>h.submit(),children:"Save Changes"})]})]})})]})]})},eQ=r(92280),eX=e=>{let{costConfig:s}=e,r=(null==s?void 0:s.default_cost_per_query)!==void 0&&(null==s?void 0:s.default_cost_per_query)!==null,l=(null==s?void 0:s.tool_name_to_cost_per_query)&&Object.keys(s.tool_name_to_cost_per_query).length>0;return r||l?(0,t.jsx)("div",{className:"mt-6 pt-6 border-t border-gray-200",children:(0,t.jsxs)("div",{className:"space-y-4",children:[r&&(null==s?void 0:s.default_cost_per_query)!==void 0&&(null==s?void 0:s.default_cost_per_query)!==null&&(0,t.jsxs)("div",{children:[(0,t.jsx)(eQ.x,{className:"font-medium",children:"Default Cost per Query"}),(0,t.jsxs)("div",{className:"text-green-600 font-mono",children:["$",s.default_cost_per_query.toFixed(4)]})]}),l&&(null==s?void 0:s.tool_name_to_cost_per_query)&&(0,t.jsxs)("div",{children:[(0,t.jsx)(eQ.x,{className:"font-medium",children:"Tool-Specific Costs"}),(0,t.jsx)("div",{className:"mt-2 space-y-2",children:Object.entries(s.tool_name_to_cost_per_query).map(e=>{let[s,r]=e;return null!=r&&(0,t.jsxs)("div",{className:"flex justify-between items-center p-3 bg-gray-50 rounded-lg",children:[(0,t.jsx)(eQ.x,{className:"font-medium",children:s}),(0,t.jsxs)(eQ.x,{className:"text-green-600 font-mono",children:["$",r.toFixed(4)," per query"]})]},s)})})]}),(0,t.jsxs)("div",{className:"mt-4 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:[(0,t.jsx)(eQ.x,{className:"text-blue-800 font-medium",children:"Cost Summary:"}),(0,t.jsxs)("div",{className:"mt-2 space-y-1",children:[r&&(null==s?void 0:s.default_cost_per_query)!==void 0&&(null==s?void 0:s.default_cost_per_query)!==null&&(0,t.jsxs)(eQ.x,{className:"text-blue-700",children:["• Default cost: $",s.default_cost_per_query.toFixed(4)," per query"]}),l&&(null==s?void 0:s.tool_name_to_cost_per_query)&&(0,t.jsxs)(eQ.x,{className:"text-blue-700",children:["• ",Object.keys(s.tool_name_to_cost_per_query).length," tool(s) with custom pricing"]})]})]})]})}):(0,t.jsx)("div",{className:"mt-6 pt-6 border-t border-gray-200",children:(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsx)("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-lg",children:(0,t.jsx)(eQ.x,{className:"text-gray-600",children:"No cost configuration set for this server. Tool calls will be charged at $0.00 per tool call."})})})})};let e0=e=>{var s,r,l,a,h;let{mcpServer:p,onBack:g,isEditing:j,isProxyAdmin:v,accessToken:y,userRole:b,userID:N,availableAccessGroups:_}=e,[w,Z]=(0,f.useState)(j),[C,S]=(0,f.useState)(!1),[k,P]=(0,f.useState)({}),[A,T]=(0,f.useState)(0),{maskedUrl:I,hasToken:M}=ec(p.url),E=(e,s)=>M?s?e:I:e,z=async(e,s)=>{await (0,eT.vQ)(e)&&(P(e=>({...e,[s]:!0})),setTimeout(()=>{P(e=>({...e,[s]:!1}))},2e3))};return(0,t.jsxs)("div",{className:"p-4 max-w-full",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(n.Z,{icon:eU.Z,variant:"light",className:"mb-4",onClick:g,children:"Back to All Servers"}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(x.Z,{children:p.server_name}),(0,t.jsx)(H.ZP,{type:"text",size:"small",icon:k["mcp-server_name"]?(0,t.jsx)(e_.Z,{size:12}):(0,t.jsx)(ew.Z,{size:12}),onClick:()=>z(p.server_name,"mcp-server_name"),className:"left-2 z-10 transition-all duration-200 ".concat(k["mcp-server_name"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100")}),p.alias&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"ml-4 text-gray-500",children:"Alias:"}),(0,t.jsx)("span",{className:"ml-1 font-mono text-blue-600",children:p.alias}),(0,t.jsx)(H.ZP,{type:"text",size:"small",icon:k["mcp-alias"]?(0,t.jsx)(e_.Z,{size:12}):(0,t.jsx)(ew.Z,{size:12}),onClick:()=>z(p.alias,"mcp-alias"),className:"left-2 z-10 transition-all duration-200 ".concat(k["mcp-alias"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100")})]})]}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(u.Z,{className:"text-gray-500 font-mono",children:p.server_id}),(0,t.jsx)(H.ZP,{type:"text",size:"small",icon:k["mcp-server-id"]?(0,t.jsx)(e_.Z,{size:12}):(0,t.jsx)(ew.Z,{size:12}),onClick:()=>z(p.server_id,"mcp-server-id"),className:"left-2 z-10 transition-all duration-200 ".concat(k["mcp-server-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100")})]})]})}),(0,t.jsxs)(o.Z,{index:A,onIndexChange:T,children:[(0,t.jsx)(c.Z,{className:"mb-4",children:[(0,t.jsx)(i.Z,{children:"Overview"},"overview"),(0,t.jsx)(i.Z,{children:"MCP Tools"},"tools"),...v?[(0,t.jsx)(i.Z,{children:"Settings"},"settings")]:[]]}),(0,t.jsxs)(m.Z,{children:[(0,t.jsxs)(d.Z,{children:[(0,t.jsxs)(eK.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(eD.Z,{children:[(0,t.jsx)(u.Z,{children:"Transport"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(x.Z,{children:O(null!==(a=p.transport)&&void 0!==a?a:void 0)})})]}),(0,t.jsxs)(eD.Z,{children:[(0,t.jsx)(u.Z,{children:"Auth Type"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(u.Z,{children:L(null!==(h=p.auth_type)&&void 0!==h?h:void 0)})})]}),(0,t.jsxs)(eD.Z,{children:[(0,t.jsx)(u.Z,{children:"Host Url"}),(0,t.jsxs)("div",{className:"mt-2 flex items-center gap-2",children:[(0,t.jsx)(u.Z,{className:"break-all overflow-wrap-anywhere",children:E(p.url,C)}),M&&(0,t.jsx)("button",{onClick:()=>S(!C),className:"p-1 hover:bg-gray-100 rounded",children:(0,t.jsx)(eH.Z,{icon:C?eV.Z:eB.Z,size:"sm",className:"text-gray-500"})})]})]})]}),(0,t.jsxs)(eD.Z,{className:"mt-2",children:[(0,t.jsx)(x.Z,{children:"Cost Configuration"}),(0,t.jsx)(eX,{costConfig:null===(s=p.mcp_info)||void 0===s?void 0:s.mcp_server_cost_info})]})]}),(0,t.jsx)(d.Z,{children:(0,t.jsx)(sZ,{serverId:p.server_id,accessToken:y,auth_type:p.auth_type,userRole:b,userID:N,serverAlias:p.alias})}),(0,t.jsx)(d.Z,{children:(0,t.jsxs)(eD.Z,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(x.Z,{children:"MCP Server Settings"}),w?null:(0,t.jsx)(n.Z,{variant:"light",onClick:()=>Z(!0),children:"Edit Settings"})]}),w?(0,t.jsx)(e$,{mcpServer:p,accessToken:y,onCancel:()=>Z(!1),onSuccess:e=>{Z(!1),g()},availableAccessGroups:_}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Server Name"}),(0,t.jsx)("div",{children:p.server_name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Alias"}),(0,t.jsx)("div",{children:p.alias})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Description"}),(0,t.jsx)("div",{children:p.description})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"URL"}),(0,t.jsxs)("div",{className:"font-mono break-all overflow-wrap-anywhere max-w-full flex items-center gap-2",children:[E(p.url,C),M&&(0,t.jsx)("button",{onClick:()=>S(!C),className:"p-1 hover:bg-gray-100 rounded",children:(0,t.jsx)(eH.Z,{icon:C?eV.Z:eB.Z,size:"sm",className:"text-gray-500"})})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Transport"}),(0,t.jsx)("div",{children:O(p.transport)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Extra Headers"}),(0,t.jsx)("div",{children:null===(r=p.extra_headers)||void 0===r?void 0:r.join(", ")})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Auth Type"}),(0,t.jsx)("div",{children:L(p.auth_type)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Allow All LiteLLM Keys"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[p.allow_all_keys?(0,t.jsx)("span",{className:"px-2 py-1 bg-green-50 text-green-700 rounded-md text-sm",children:"Enabled"}):(0,t.jsx)("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded-md text-sm",children:"Disabled"}),p.allow_all_keys&&(0,t.jsx)(u.Z,{className:"text-xs text-gray-500",children:"All keys can access this MCP server"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Available on Public Internet"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[p.available_on_public_internet?(0,t.jsx)("span",{className:"px-2 py-1 bg-green-50 text-green-700 rounded-md text-sm",children:"Public"}):(0,t.jsx)("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded-md text-sm",children:"Internal"}),p.available_on_public_internet&&(0,t.jsx)(u.Z,{className:"text-xs text-gray-500",children:"Accessible from external/public IPs"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Access Groups"}),(0,t.jsx)("div",{children:p.mcp_access_groups&&p.mcp_access_groups.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:p.mcp_access_groups.map((e,s)=>{var r;return(0,t.jsx)("span",{className:"px-2 py-1 bg-gray-100 rounded-md text-sm",children:"string"==typeof e?e:null!==(r=null==e?void 0:e.name)&&void 0!==r?r:""},s)})}):(0,t.jsx)(u.Z,{className:"text-gray-500",children:"No access groups defined"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Allowed Tools"}),(0,t.jsx)("div",{children:p.allowed_tools&&p.allowed_tools.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:p.allowed_tools.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-50 border border-blue-200 rounded-md text-sm",children:e},s))}):(0,t.jsx)(u.Z,{className:"text-gray-500",children:"All tools enabled"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(u.Z,{className:"font-medium",children:"Cost Configuration"}),(0,t.jsx)(eX,{costConfig:null===(l=p.mcp_info)||void 0===l?void 0:l.mcp_server_cost_info})]})]})]})})]})]})]})},e2=(0,N.n)("mcpSemanticFilterSettings"),e1=()=>{let{accessToken:e}=(0,w.Z)();return(0,b.a)({queryKey:e2.list({}),queryFn:async()=>await (0,_.getMCPSemanticFilterSettings)(e),enabled:!!e,staleTime:36e5,gcTime:36e5})};var e4=r(29827),e5=r(21770);let e6=(0,N.n)("mcpSemanticFilterSettings"),e3=e=>{let s=(0,e4.NL)();return(0,e5.D)({mutationFn:async s=>{if(!e)throw Error("Access token is required");return(0,_.updateMCPSemanticFilterSettings)(e,s)},onSuccess:()=>{s.invalidateQueries({queryKey:e6.all})}})};var e8=r(50337),e7=r(47451),e9=r(69410),se=r(85847),ss=r(78355),sr=r(10703),st=r(28595),sl=r(11894),sa=r(65869),sn=r(76593);function si(e){let{accessToken:s,testQuery:r,setTestQuery:l,testModel:a,setTestModel:n,isTesting:i,onTest:o,filterEnabled:c,testResult:d,curlCommand:m}=e;return(0,t.jsx)(eb.Z,{title:"Test Configuration",style:{marginBottom:16},children:(0,t.jsx)(sa.default,{defaultActiveKey:"test",items:[{key:"test",label:"Test",children:(0,t.jsxs)(er.Z,{direction:"vertical",style:{width:"100%"},size:"large",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)(h.default.Text,{strong:!0,style:{display:"block",marginBottom:8},children:[(0,t.jsx)(st.Z,{})," Test Query"]}),(0,t.jsx)(A.default.TextArea,{placeholder:"Enter a test query to see which tools would be selected...",value:r,onChange:e=>l(e.target.value),rows:4,disabled:i})]}),(0,t.jsx)("div",{children:(0,t.jsx)(sn.Z,{accessToken:s||"",value:a,onChange:n,disabled:i,showLabel:!0,labelText:"Select Model"})}),(0,t.jsx)(H.ZP,{type:"primary",icon:(0,t.jsx)(st.Z,{}),onClick:o,loading:i,disabled:!r||!a||!c,block:!0,children:"Test Filter"}),!c&&(0,t.jsx)(K.Z,{type:"warning",message:"Semantic filtering is disabled",description:"Enable semantic filtering and save settings to test the filter.",showIcon:!0}),d&&(0,t.jsxs)("div",{children:[(0,t.jsx)(h.default.Title,{level:5,children:"Results"}),(0,t.jsx)(K.Z,{type:"success",message:"".concat(d.selectedTools," tools selected"),description:"Filtered from ".concat(d.totalTools," available tools"),showIcon:!0,style:{marginBottom:16}}),(0,t.jsxs)("div",{children:[(0,t.jsx)(h.default.Text,{strong:!0,style:{display:"block",marginBottom:8},children:"Selected Tools:"}),(0,t.jsx)("ul",{style:{paddingLeft:20,margin:0},children:d.tools.map((e,s)=>(0,t.jsx)("li",{style:{marginBottom:4},children:(0,t.jsx)(h.default.Text,{children:e})},s))})]})]})]})},{key:"api",label:"API Usage",children:(0,t.jsxs)("div",{children:[(0,t.jsxs)(er.Z,{style:{marginBottom:8},children:[(0,t.jsx)(sl.Z,{}),(0,t.jsx)(h.default.Text,{strong:!0,children:"API Usage"})]}),(0,t.jsx)(h.default.Text,{type:"secondary",style:{display:"block",marginBottom:8},children:"Use this curl command to test the semantic filter with your current configuration."}),(0,t.jsx)(h.default.Text,{strong:!0,style:{display:"block",marginBottom:8},children:"Response headers to check:"}),(0,t.jsxs)("ul",{style:{paddingLeft:20,margin:"0 0 12px 0"},children:[(0,t.jsxs)("li",{children:[(0,t.jsx)(h.default.Text,{children:"x-litellm-semantic-filter: shows total tools → selected tools"}),(0,t.jsx)(h.default.Text,{type:"secondary",style:{display:"block"},children:"Example: 10→3"})]}),(0,t.jsxs)("li",{children:[(0,t.jsx)(h.default.Text,{children:"x-litellm-semantic-filter-tools: CSV of selected tool names"}),(0,t.jsx)(h.default.Text,{type:"secondary",style:{display:"block"},children:"Example: wikipedia-fetch,github-search,slack-post"})]})]}),(0,t.jsx)("pre",{style:{background:"#f5f5f5",padding:12,borderRadius:4,overflow:"auto",fontSize:12,margin:0},children:m})]})}]})})}let so=e=>{if(!e.filter)return null;let[s,r]=e.filter.split("->").map(Number);return{totalTools:s,selectedTools:r,tools:e.tools?e.tools.split(",").map(e=>e.trim()):[]}},sc=async e=>{let{accessToken:s,testModel:r,testQuery:t,setIsTesting:l,setTestResult:a}=e;if(!t||!r||!s){S.ZP.error("Please enter a query and select a model");return}l(!0),a(null);try{let{headers:e}=await (0,_.testMCPSemanticFilter)(s,r,t),l=so(e);if(!l){S.ZP.warning("Semantic filter is not enabled or no tools were filtered");return}a(l),S.ZP.success("Semantic filter test completed successfully")}catch(e){console.error("Test failed:",e),S.ZP.error("Failed to test semantic filter")}finally{l(!1)}},sd=(e,s)=>"curl --location 'http://localhost:4000/v1/responses' \\\n--header 'Content-Type: application/json' \\\n--header 'Authorization: Bearer sk-1234' \\\n--data '{\n \"model\": \"".concat(e,'",\n "input": [\n {\n "role": "user",\n "content": "').concat(s||"Your query here",'",\n "type": "message"\n }\n ],\n "tools": [\n {\n "type": "mcp",\n "server_url": "litellm_proxy",\n "require_approval": "never"\n }\n ],\n "tool_choice": "required"\n}\'');function sm(e){var s,r,l;let{accessToken:n}=e,{data:i,isLoading:o,isError:c,error:d}=e1(),{mutate:m,isPending:u,error:x}=e3(n||""),[g]=P.Z.useForm(),[j,y]=(0,f.useState)(!1),[b,N]=(0,f.useState)(!1),[_,w]=(0,f.useState)([]),[Z,C]=(0,f.useState)(!0),[k,A]=(0,f.useState)(""),[T,I]=(0,f.useState)("gpt-4o"),[M,E]=(0,f.useState)(null),[O,L]=(0,f.useState)(!1),F=null==i?void 0:i.field_schema,q=null!==(l=null==i?void 0:i.values)&&void 0!==l?l:{};(0,f.useEffect)(()=>{(async()=>{if(n)try{C(!0);let e=(await (0,sr.p)(n)).filter(e=>"embedding"===e.mode);w(e)}catch(e){console.error("Error fetching embedding models:",e)}finally{C(!1)}})()},[n]),(0,f.useEffect)(()=>{if(q){var e,s,r,t;g.setFieldsValue({enabled:null!==(e=q.enabled)&&void 0!==e&&e,embedding_model:null!==(s=q.embedding_model)&&void 0!==s?s:"text-embedding-3-small",top_k:null!==(r=q.top_k)&&void 0!==r?r:10,similarity_threshold:null!==(t=q.similarity_threshold)&&void 0!==t?t:.3}),N(!1)}},[q,g]);let R=async()=>{try{let e=await g.validateFields();m(e,{onSuccess:()=>{N(!1),y(!0),setTimeout(()=>y(!1),3e3),S.ZP.success("Settings updated successfully. Changes will be applied across all pods within 10 seconds.")},onError:e=>{S.ZP.fromBackend(e)}})}catch(e){console.error("Form validation failed:",e)}},U=async()=>{n&&await sc({accessToken:n,testModel:T,testQuery:k,setIsTesting:L,setTestResult:E})};return n?(0,t.jsx)("div",{style:{width:"100%"},children:o?(0,t.jsx)(e8.Z,{active:!0}):c?(0,t.jsx)(K.Z,{type:"error",message:"Could not load MCP Semantic Filter settings",description:d instanceof Error?d.message:void 0,style:{marginBottom:24}}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(K.Z,{type:"info",message:"Semantic Tool Filtering",description:"Filter MCP tools semantically based on query relevance. This reduces context window size and improves tool selection accuracy. Click 'Save Settings' to apply changes across all pods (takes effect within 10 seconds).",showIcon:!0,style:{marginBottom:24}}),j&&(0,t.jsx)(K.Z,{type:"success",message:"Settings saved successfully",icon:(0,t.jsx)(J.Z,{}),showIcon:!0,closable:!0,style:{marginBottom:16}}),x&&(0,t.jsx)(K.Z,{type:"error",message:"Could not update settings",description:x instanceof Error?x.message:void 0,style:{marginBottom:16}}),(0,t.jsxs)(e7.Z,{gutter:24,children:[(0,t.jsx)(e9.Z,{xs:24,lg:12,children:(0,t.jsxs)(P.Z,{form:g,layout:"vertical",disabled:u,onValuesChange:()=>{N(!0)},children:[(0,t.jsxs)(eb.Z,{style:{marginBottom:16},children:[(0,t.jsx)(P.Z.Item,{name:"enabled",label:(0,t.jsxs)(er.Z,{children:[(0,t.jsx)(h.default.Text,{strong:!0,children:"Enable Semantic Filtering"}),(0,t.jsx)(v.Z,{title:"When enabled, only the most relevant MCP tools will be included in requests based on semantic similarity",children:(0,t.jsx)(a.Z,{style:{color:"#8c8c8c"}})})]}),valuePropName:"checked",children:(0,t.jsx)(es.Z,{disabled:u})}),(0,t.jsx)(h.default.Text,{type:"secondary",style:{display:"block",marginTop:-16,marginBottom:16},children:null==F?void 0:null===(r=F.properties)||void 0===r?void 0:null===(s=r.enabled)||void 0===s?void 0:s.description})]}),(0,t.jsxs)(eb.Z,{title:"Configuration",style:{marginBottom:16},children:[(0,t.jsx)(P.Z.Item,{name:"embedding_model",label:(0,t.jsxs)(er.Z,{children:[(0,t.jsx)(h.default.Text,{strong:!0,children:"Embedding Model"}),(0,t.jsx)(v.Z,{title:"The model used to generate embeddings for semantic matching",children:(0,t.jsx)(a.Z,{style:{color:"#8c8c8c"}})})]}),children:(0,t.jsx)(p.default,{options:_.map(e=>({label:e.model_group,value:e.model_group})),placeholder:Z?"Loading models...":"Select embedding model",showSearch:!0,disabled:u||Z,loading:Z,notFoundContent:Z?"Loading...":"No embedding models available"})}),(0,t.jsx)(P.Z.Item,{name:"top_k",label:(0,t.jsxs)(er.Z,{children:[(0,t.jsx)(h.default.Text,{strong:!0,children:"Top K Results"}),(0,t.jsx)(v.Z,{title:"Maximum number of tools to return after filtering",children:(0,t.jsx)(a.Z,{style:{color:"#8c8c8c"}})})]}),children:(0,t.jsx)(z.Z,{min:1,max:100,style:{width:"100%"},disabled:u})}),(0,t.jsx)(P.Z.Item,{name:"similarity_threshold",label:(0,t.jsxs)(er.Z,{children:[(0,t.jsx)(h.default.Text,{strong:!0,children:"Similarity Threshold"}),(0,t.jsx)(v.Z,{title:"Minimum similarity score (0-1) for a tool to be included",children:(0,t.jsx)(a.Z,{style:{color:"#8c8c8c"}})})]}),children:(0,t.jsx)(se.Z,{min:0,max:1,step:.05,marks:{0:"0.0",.3:"0.3",.5:"0.5",.7:"0.7",1:"1.0"},disabled:u})})]}),(0,t.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:(0,t.jsx)(H.ZP,{type:"primary",icon:(0,t.jsx)(ss.Z,{}),onClick:R,loading:u,disabled:!b,children:"Save Settings"})})]})}),(0,t.jsx)(e9.Z,{xs:24,lg:12,children:(0,t.jsx)(si,{accessToken:n,testQuery:k,setTestQuery:A,testModel:T,setTestModel:I,isTesting:O,onTest:U,filterEnabled:!!q.enabled,testResult:M,curlCommand:sd(T,k)})})]})]})}):(0,t.jsx)("div",{className:"p-6 text-center text-gray-500",children:"Please log in to configure semantic filter settings."})}var su=r(3810);let{Text:sx}=h.default;var sh=e=>{let{accessToken:s}=e,[r,l]=(0,f.useState)(!0),[a,n]=(0,f.useState)(!1),[i,o]=(0,f.useState)([]),[c,d]=(0,f.useState)(null);(0,f.useEffect)(()=>{m(),u()},[s]);let m=async()=>{if(s){l(!0);try{for(let e of(await (0,_.getGeneralSettingsCall)(s)))"mcp_internal_ip_ranges"===e.field_name&&e.field_value&&o(e.field_value)}catch(e){console.error("Failed to load MCP network settings:",e)}finally{l(!1)}}},u=async()=>{if(!s)return;let e=await (0,_.fetchMCPClientIp)(s);e&&d(e)},x=async()=>{if(s){n(!0);try{i.length>0?await (0,_.updateConfigFieldSetting)(s,"mcp_internal_ip_ranges",i):await (0,_.deleteConfigFieldSetting)(s,"mcp_internal_ip_ranges")}catch(e){console.error("Failed to save MCP network settings:",e)}finally{n(!1)}}},h=e=>{i.includes(e)||o([...i,e])};if(r)return(0,t.jsx)("div",{className:"flex justify-center py-12",children:(0,t.jsx)(D.Z,{})});let g=c?function(e){let s=e.split(".");return 4!==s.length?e+"/32":"".concat(s[0],".").concat(s[1],".").concat(s[2],".0/24")}(c):null;return(0,t.jsxs)("div",{className:"space-y-6 p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(sx,{className:"text-lg font-semibold",children:"Private IP Ranges"}),(0,t.jsx)("p",{className:"text-sm text-gray-500 mt-1",children:'Define which IP ranges are part of your private network. Callers from these IPs can see all MCP servers. Callers from any other IP can only see servers marked "Available on Public Internet".'})]}),(0,t.jsxs)(eb.Z,{children:[c&&(0,t.jsxs)("div",{className:"mb-4 p-3 bg-blue-50 rounded-lg",children:[(0,t.jsxs)(sx,{className:"text-sm text-blue-700",children:["Your current IP: ",(0,t.jsx)("span",{className:"font-mono font-medium",children:c})]}),g&&!i.includes(g)&&(0,t.jsxs)("div",{className:"mt-1",children:[(0,t.jsx)(sx,{className:"text-sm text-blue-600",children:"Suggested range: "}),(0,t.jsx)(su.Z,{className:"cursor-pointer font-mono",color:"blue",icon:(0,t.jsx)(el.Z,{}),onClick:()=>h(g),children:g})]})]}),(0,t.jsx)("div",{className:"flex items-center mb-2",children:(0,t.jsx)(sx,{className:"font-medium",children:"Your Private Network Ranges"})}),(0,t.jsx)(p.default,{mode:"tags",value:i,onChange:o,placeholder:"Leave empty to use defaults: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8",tokenSeparators:[","],className:"w-full",size:"large",allowClear:!0}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mt-2",children:"Enter CIDR ranges (e.g., 10.0.0.0/8). When empty, standard private IP ranges are used."})]}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)(H.ZP,{type:"primary",icon:(0,t.jsx)(ss.Z,{}),onClick:x,loading:a,children:"Save"})})]})};let{Text:sp,Title:sg}=h.default,{Option:sj}=p.default;var sv=e=>{let{accessToken:s,userRole:r,userID:h}=e,{data:b,isLoading:N,refetch:w}=(0,y.F)(),{data:Z,isLoading:P}=C((0,f.useMemo)(()=>null==b?void 0:b.map(e=>e.server_id),[b])),A=(0,f.useMemo)(()=>{if(!b)return[];if(!Z)return b;let e=new Map(Z.map(e=>[e.server_id,e.status]));return b.map(s=>{let r=e.get(s.server_id);return{...s,status:r||s.status}})},[b,Z]);f.useEffect(()=>{b&&(console.log("MCP Servers fetched:",b),b.forEach(e=>{console.log("Server: ".concat(e.server_name||e.server_id)),console.log(" allowed_tools:",e.allowed_tools)}))},[b]);let[T,I]=(0,f.useState)(null),[M,E]=(0,f.useState)(!1),[O,L]=(0,f.useState)(null),[z,F]=(0,f.useState)(!1),[q,R]=(0,f.useState)("all"),[U,V]=(0,f.useState)("all"),[B,D]=(0,f.useState)([]),[K,H]=(0,f.useState)(!1),[J,G]=(0,f.useState)(!1),Y="Internal User"===r;(0,f.useEffect)(()=>{try{let e=window.sessionStorage.getItem("litellm-mcp-oauth-edit-state");if(!e)return;let s=JSON.parse(e);(null==s?void 0:s.serverId)&&(L(s.serverId),F(!0))}catch(e){console.error("Failed to restore MCP edit view state",e)}},[]);let W=f.useMemo(()=>{if(!A)return[];let e=new Set,s=[];return A.forEach(r=>{r.teams&&r.teams.forEach(r=>{let t=r.team_id;e.has(t)||(e.add(t),s.push(r))})}),s},[A]),$=f.useMemo(()=>A?Array.from(new Set(A.flatMap(e=>e.mcp_access_groups).filter(e=>null!=e))):[],[A]),Q=(0,f.useCallback)((e,s)=>{if(!A)return D([]);let r=A;if("personal"===e){D([]);return}"all"!==e&&(r=r.filter(s=>{var r;return null===(r=s.teams)||void 0===r?void 0:r.some(s=>s.team_id===e)})),"all"!==s&&(r=r.filter(e=>{var r;return null===(r=e.mcp_access_groups)||void 0===r?void 0:r.some(e=>"string"==typeof e?e===s:e&&e.name===s)})),D(r)},[A]);(0,f.useEffect)(()=>{Q(q,U)},[A,q,U,Q]);let X=f.useMemo(()=>eR(null!=r?r:"",e=>{L(e),F(!1)},e=>{L(e),F(!0)},ee,P),[r,P]);function ee(e){I(e),E(!0)}let es=async()=>{if(null!=T&&null!=s)try{G(!0),await (0,_.deleteMCPServer)(s,T),S.ZP.success("Deleted MCP Server successfully"),w()}catch(e){console.error("Error deleting the mcp server:",e)}finally{G(!1),E(!1),I(null)}},er=T?(b||[]).find(e=>e.server_id===T):null,et=f.useMemo(()=>B.find(e=>e.server_id===O)||{server_id:"",server_name:"",alias:"",url:"",transport:"",auth_type:"",created_at:"",created_by:"",updated_at:"",updated_by:""},[B,O]),el=f.useCallback(()=>{F(!1),L(null),w()},[w]);return s&&r&&h?(0,t.jsxs)("div",{className:"w-full h-full p-6",children:[(0,t.jsx)(g.Z,{open:M,title:"Delete MCP Server?",onOk:es,okText:J?"Deleting...":"Delete",onCancel:()=>{E(!1),I(null)},cancelText:"Cancel",cancelButtonProps:{disabled:J},okButtonProps:{danger:!0},confirmLoading:J,children:(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(sp,{children:"Are you sure you want to delete this MCP Server? This action cannot be undone."}),er&&(0,t.jsxs)("div",{className:"mt-4 p-4 bg-red-50 rounded-lg border border-red-200",children:[(0,t.jsx)(sg,{level:5,className:"mb-3 text-gray-900",children:"Server Information"}),(0,t.jsxs)(j.Z,{column:1,size:"small",children:[er.server_name&&(0,t.jsx)(j.Z.Item,{label:(0,t.jsx)("span",{className:"font-semibold text-gray-700",children:"Server Name"}),children:(0,t.jsx)(sp,{className:"text-sm",children:er.server_name})}),er.alias&&(0,t.jsx)(j.Z.Item,{label:(0,t.jsx)("span",{className:"font-semibold text-gray-700",children:"Alias"}),children:(0,t.jsx)(sp,{className:"text-sm",children:er.alias})}),(0,t.jsx)(j.Z.Item,{label:(0,t.jsx)("span",{className:"font-semibold text-gray-700",children:"Server ID"}),children:(0,t.jsx)(sp,{code:!0,className:"text-sm",children:er.server_id})}),(0,t.jsx)(j.Z.Item,{label:(0,t.jsx)("span",{className:"font-semibold text-gray-700",children:"URL"}),children:(0,t.jsx)(sp,{code:!0,className:"text-sm",children:er.url})})]})]})]})}),(0,t.jsx)(ey,{userRole:r,accessToken:s,onCreateSuccess:e=>{D(s=>[...s,e]),H(!1)},isModalVisible:K,setModalVisible:H,availableAccessGroups:$}),(0,t.jsx)(x.Z,{children:"MCP Servers"}),(0,t.jsx)(u.Z,{className:"text-tremor-content mt-2",children:"Configure and manage your MCP servers"}),(0,l.tY)(r)&&(0,t.jsx)(n.Z,{className:"mt-4 mb-4",onClick:()=>H(!0),children:"+ Add New MCP Server"}),(0,t.jsxs)(o.Z,{className:"w-full h-full",children:[(0,t.jsx)(c.Z,{className:"flex justify-between mt-2 w-full items-center",children:(0,t.jsxs)("div",{className:"flex",children:[(0,t.jsx)(i.Z,{children:"All Servers"}),(0,t.jsx)(i.Z,{children:"Connect"}),(0,t.jsx)(i.Z,{children:"Semantic Filter"}),(0,t.jsx)(i.Z,{children:"Network Settings"})]})}),(0,t.jsxs)(m.Z,{children:[(0,t.jsx)(d.Z,{children:O?(0,t.jsx)(e0,{mcpServer:et,onBack:el,isProxyAdmin:(0,l.tY)(r),isEditing:z,accessToken:s,userID:h,userRole:r,availableAccessGroups:$},O):(0,t.jsxs)("div",{className:"w-full h-full",children:[(0,t.jsx)("div",{className:"w-full px-6",children:(0,t.jsx)("div",{className:"flex flex-col space-y-4",children:(0,t.jsx)("div",{className:"flex items-center justify-between bg-gray-50 rounded-lg p-4 border-2 border-gray-200",children:(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)(u.Z,{className:"text-lg font-semibold text-gray-900",children:"Current Team:"}),(0,t.jsxs)(p.default,{value:q,onChange:e=>{R(e),Q(e,U)},style:{width:300},children:[(0,t.jsx)(sj,{value:"all",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:Y?"All Available Servers":"All Servers"})]})}),(0,t.jsx)(sj,{value:"personal",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:"Personal"})]})}),W.map(e=>(0,t.jsx)(sj,{value:e.team_id,children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:e.team_alias||e.team_id})]})},e.team_id))]}),(0,t.jsxs)(u.Z,{className:"text-lg font-semibold text-gray-900 ml-6",children:["Access Group:",(0,t.jsx)(v.Z,{title:"An MCP Access Group is a set of users or teams that have permission to access specific MCP servers. Use access groups to control and organize who can connect to which servers.",children:(0,t.jsx)(a.Z,{style:{marginLeft:4,color:"#888"}})})]}),(0,t.jsxs)(p.default,{value:U,onChange:e=>{V(e),Q(q,e)},style:{width:300},children:[(0,t.jsx)(sj,{value:"all",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:"All Access Groups"})]})}),$.map(e=>(0,t.jsx)(sj,{value:e,children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{className:"font-medium",children:e})]})},e))]})]})})})}),(0,t.jsx)("div",{className:"w-full px-6 mt-6",children:(0,t.jsx)(k.w,{data:B,columns:X,renderSubComponent:()=>(0,t.jsx)("div",{}),getRowCanExpand:()=>!1,isLoading:N,noDataMessage:"No MCP servers configured",loadingMessage:"\uD83D\uDE85 Loading MCP servers..."})})]})}),(0,t.jsx)(d.Z,{children:(0,t.jsx)(eL,{})}),(0,t.jsx)(d.Z,{children:(0,t.jsx)(sm,{accessToken:s})}),(0,t.jsx)(d.Z,{children:(0,t.jsx)(sh,{accessToken:s})})]})]})]}):(console.log("Missing required authentication parameters",{accessToken:s,userRole:r,userID:h}),(0,t.jsx)("div",{className:"p-6 text-center text-gray-500",children:"Missing required authentication parameters."}))};let sf=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function sy(e){if(!e)return[];if(Array.isArray(e))return e.map(e=>sb(e)).filter(e=>void 0!==e);let s=sb(e);return void 0===s?[]:[s]}function sb(e,s){if(!e)return;let r=void 0!==s?s:e.default;if("object"===e.type){let s=sf(r)?{...r}:{};return e.properties&&Object.entries(e.properties).forEach(e=>{let[r,t]=e;s[r]=sb(t,s[r])}),s}if("array"===e.type){if(Array.isArray(r)){let s=e.items;if(!s)return r;if(0===r.length){let e=sy(s);return e.length?e:r}return Array.isArray(s)?r.map((e,r)=>{var t;return sb(null!==(t=s[r])&&void 0!==t?t:s[s.length-1],e)}):r.map(e=>sb(s,e))}return void 0!==r?r:sy(e.items)}if(void 0!==r)return r;switch(e.type){case"integer":case"number":return 0;case"boolean":return!1;default:return""}}let sN=e=>{let s=sb(e);if("object"===e.type||"array"===e.type){let r="array"===e.type?[]:{};return JSON.stringify(null!=s?s:r,null,2)}return s};function s_(e){let{tool:s,onSubmit:r,isLoading:l,result:a,error:n,onClose:i}=e,[o]=P.Z.useForm(),[c,d]=f.useState("formatted"),[m,u]=f.useState(null),[x,h]=f.useState(null),p=f.useMemo(()=>"string"==typeof s.inputSchema?{type:"object",properties:{input:{type:"string",description:"Input for this tool"}},required:["input"]}:s.inputSchema,[s.inputSchema]),g=f.useMemo(()=>p.properties&&p.properties.params&&"object"===p.properties.params.type&&p.properties.params.properties?{type:"object",properties:p.properties.params.properties,required:p.properties.params.required||[]}:p,[p]);f.useEffect(()=>{if(o.resetFields(),!g.properties)return;let e={};Object.entries(g.properties).forEach(s=>{let[r,t]=s;e[r]=sN(t)}),o.setFieldsValue(e)},[o,g,s]),f.useEffect(()=>{m&&(a||n)&&h(Date.now()-m)},[a,n,m]);let j=async e=>{try{if(navigator.clipboard&&window.isSecureContext)return await navigator.clipboard.writeText(e),!0;{let s=document.createElement("textarea");s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.focus(),s.select();let r=document.execCommand("copy");if(document.body.removeChild(s),!r)throw Error("execCommand failed");return!0}}catch(e){return console.error("Copy failed:",e),!1}},y=async()=>{await j(JSON.stringify(a,null,2))?S.ZP.success("Result copied to clipboard"):S.ZP.fromBackend("Failed to copy result")},b=async()=>{await j(s.name)?S.ZP.success("Tool name copied to clipboard"):S.ZP.fromBackend("Failed to copy tool name")};return(0,t.jsxs)("div",{className:"space-y-4 h-full",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between pb-3 border-b border-gray-200",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-3",children:[s.mcp_info.logo_url&&(0,t.jsx)("img",{src:s.mcp_info.logo_url,alt:"".concat(s.mcp_info.server_name," logo"),className:"w-6 h-6 object-contain"}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-1",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-gray-900",children:"Test Tool:"}),(0,t.jsxs)("div",{className:"group inline-flex items-center space-x-1 bg-slate-50 hover:bg-slate-100 px-3 py-1 rounded-md cursor-pointer transition-colors border border-slate-200",onClick:b,title:"Click to copy tool name",children:[(0,t.jsx)("span",{className:"font-mono text-slate-700 font-medium text-sm",children:s.name}),(0,t.jsx)("svg",{className:"w-3 h-3 text-slate-400 group-hover:text-slate-600 transition-colors",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})]})]}),(0,t.jsx)("p",{className:"text-xs text-gray-600",children:s.description}),(0,t.jsxs)("p",{className:"text-xs text-gray-500",children:["Provider: ",s.mcp_info.server_name]})]})]}),(0,t.jsx)(I.z,{onClick:i,variant:"light",size:"sm",className:"text-gray-500 hover:text-gray-700",children:(0,t.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 h-full",children:[(0,t.jsxs)("div",{className:"bg-white border border-gray-200 rounded-lg",children:[(0,t.jsx)("div",{className:"border-b border-gray-100 px-4 py-2",children:(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold text-gray-900",children:"Input Parameters"}),(0,t.jsx)(v.Z,{title:"Configure the input parameters for this tool call",children:(0,t.jsx)(T.Z,{className:"text-gray-400 hover:text-gray-600"})})]})}),(0,t.jsx)("div",{className:"p-4",children:(0,t.jsxs)(P.Z,{form:o,onFinish:e=>{u(Date.now()),h(null);let s={};Object.entries(e).forEach(e=>{var r;let[t,l]=e,a=null===(r=g.properties)||void 0===r?void 0:r[t];if(a&&null!=l&&""!==l)switch(a.type){case"boolean":s[t]="true"===l||!0===l;break;case"number":case"integer":{let e=Number(l);s[t]=Number.isNaN(e)?l:"integer"===a.type?Math.trunc(e):e;break}case"object":case"array":try{let e="string"==typeof l?JSON.parse(l):l,r="object"===a.type&&null!==e&&"object"==typeof e&&!Array.isArray(e),n="array"===a.type&&Array.isArray(e);"object"===a.type&&r||"array"===a.type&&n?s[t]=e:s[t]=l}catch(e){s[t]=l}break;case"string":s[t]=String(l);break;default:s[t]=l}else null!=l&&""!==l&&(s[t]=l)}),r(p.properties&&p.properties.params&&"object"===p.properties.params.type&&p.properties.params.properties?{params:s}:s)},layout:"vertical",className:"space-y-3",children:["string"==typeof s.inputSchema?(0,t.jsx)("div",{className:"space-y-3",children:(0,t.jsx)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700",children:["Input ",(0,t.jsx)("span",{className:"text-red-500",children:"*"})]}),name:"input",rules:[{required:!0,message:"Please enter input for this tool"}],className:"mb-3",children:(0,t.jsx)(I.o,{placeholder:"Enter input for this tool",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})})}):void 0===g.properties?(0,t.jsx)("div",{className:"text-center py-6 bg-gray-50 rounded-lg border border-gray-200",children:(0,t.jsxs)("div",{className:"max-w-sm mx-auto",children:[(0,t.jsx)("h4",{className:"text-sm font-medium text-gray-900 mb-1",children:"No Parameters Required"}),(0,t.jsx)("p",{className:"text-xs text-gray-500",children:"This tool can be called without any input parameters."})]})}):(0,t.jsx)("div",{className:"space-y-3",children:Object.entries(g.properties).map(e=>{var r,l,a,n;let[i,o]=e,c=sN(o),d="".concat(s.name,"-").concat(i);return(0,t.jsxs)(P.Z.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:[i," ",(null===(r=g.required)||void 0===r?void 0:r.includes(i))&&(0,t.jsx)("span",{className:"text-red-500",children:"*"}),o.description&&(0,t.jsx)(v.Z,{title:o.description,children:(0,t.jsx)(T.Z,{className:"ml-2 text-gray-400 hover:text-gray-600"})})]}),name:i,initialValue:c,rules:[{required:null===(l=g.required)||void 0===l?void 0:l.includes(i),message:"Please enter ".concat(i)},..."object"===o.type||"array"===o.type?[{validator:(e,s)=>{var r;if((null==s||""===s)&&!(null===(r=g.required)||void 0===r?void 0:r.includes(i)))return Promise.resolve();try{let e="string"==typeof s?JSON.parse(s):s,r="object"===o.type&&null!==e&&"object"==typeof e&&!Array.isArray(e),t="array"===o.type&&Array.isArray(e);if("object"===o.type&&r||"array"===o.type&&t)return Promise.resolve();return Promise.reject(Error("object"===o.type?"Please enter a JSON object":"Please enter a JSON array"))}catch(e){return Promise.reject(Error("Invalid JSON"))}}}]:[]],className:"mb-3",children:["string"===o.type&&o.enum&&(0,t.jsxs)("select",{className:"w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition-colors",defaultValue:null!=c?c:"",children:[!(null===(a=g.required)||void 0===a?void 0:a.includes(i))&&(0,t.jsxs)("option",{value:"",children:["Select ",i]}),o.enum.map(e=>(0,t.jsx)("option",{value:e,children:e},e))]}),"string"===o.type&&!o.enum&&(0,t.jsx)(I.o,{placeholder:o.description||"Enter ".concat(i),defaultValue:null!=c?c:"",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"}),("number"===o.type||"integer"===o.type)&&(0,t.jsx)("input",{type:"number",step:"integer"===o.type?1:"any",placeholder:o.description||"Enter ".concat(i),defaultValue:null!=c?c:0,className:"w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition-colors"}),"boolean"===o.type&&(0,t.jsxs)("select",{className:"w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition-colors",defaultValue:(null!=c&&c).toString(),children:[!(null===(n=g.required)||void 0===n?void 0:n.includes(i))&&(0,t.jsxs)("option",{value:"",children:["Select ",i]}),(0,t.jsx)("option",{value:"true",children:"True"}),(0,t.jsx)("option",{value:"false",children:"False"})]}),("object"===o.type||"array"===o.type)&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("textarea",{rows:"object"===o.type?6:4,placeholder:o.description||("object"===o.type?"Enter JSON object for ".concat(i):"Enter JSON array for ".concat(i)),defaultValue:null!=c?c:"object"===o.type?"{}":"[]",spellCheck:!1,"data-testid":"textarea-".concat(i),className:"w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm font-mono"}),(0,t.jsx)("p",{className:"text-xs text-gray-500",children:"object"===o.type?"Provide a valid JSON object.":"Provide a valid JSON array."})]})]},d)})}),(0,t.jsx)("div",{className:"pt-3 border-t border-gray-100",children:(0,t.jsx)(I.z,{onClick:()=>o.submit(),disabled:l,variant:"primary",className:"w-full",loading:l,children:l?"Calling Tool...":a||n?"Call Again":"Call Tool"})})]})})]}),(0,t.jsxs)("div",{className:"bg-white border border-gray-200 rounded-lg",children:[(0,t.jsx)("div",{className:"border-b border-gray-100 px-4 py-2",children:(0,t.jsx)("h3",{className:"text-sm font-semibold text-gray-900",children:"Tool Result"})}),(0,t.jsx)("div",{className:"p-4",children:a||n||l?(0,t.jsxs)("div",{className:"space-y-3",children:[a&&!l&&!n&&(0,t.jsx)("div",{className:"p-2 bg-green-50 border border-green-200 rounded-lg",children:(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("svg",{className:"h-4 w-4 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),(0,t.jsx)("h4",{className:"text-xs font-medium text-green-900",children:"Tool executed successfully"}),null!==x&&(0,t.jsxs)("span",{className:"text-xs text-green-600 ml-1",children:["• ",(x/1e3).toFixed(2),"s"]})]}),(0,t.jsxs)("div",{className:"flex items-center space-x-1",children:[(0,t.jsxs)("div",{className:"flex bg-white rounded border border-green-300 p-0.5",children:[(0,t.jsx)("button",{onClick:()=>d("formatted"),className:"px-2 py-1 text-xs font-medium rounded transition-colors ".concat("formatted"===c?"bg-green-100 text-green-800":"text-green-600 hover:text-green-800"),children:"Formatted"}),(0,t.jsx)("button",{onClick:()=>d("json"),className:"px-2 py-1 text-xs font-medium rounded transition-colors ".concat("json"===c?"bg-green-100 text-green-800":"text-green-600 hover:text-green-800"),children:"JSON"})]}),(0,t.jsx)("button",{onClick:y,className:"p-1 hover:bg-green-100 rounded text-green-700",title:"Copy response",children:(0,t.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,t.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})]})}),(0,t.jsxs)("div",{className:"max-h-96 overflow-y-auto",children:[l&&(0,t.jsxs)("div",{className:"flex flex-col justify-center items-center h-48 text-gray-500",children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-gray-200"}),(0,t.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-blue-600 border-t-transparent absolute top-0"})]}),(0,t.jsx)("p",{className:"text-sm font-medium mt-3",children:"Calling tool..."}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mt-1",children:"Please wait while we process your request"})]}),n&&(0,t.jsx)("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:(0,t.jsxs)("div",{className:"flex items-start space-x-2",children:[(0,t.jsx)("div",{className:"flex-shrink-0",children:(0,t.jsx)("svg",{className:"h-4 w-4 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-1",children:[(0,t.jsx)("h4",{className:"text-xs font-medium text-red-900",children:"Tool Call Failed"}),null!==x&&(0,t.jsxs)("span",{className:"text-xs text-red-600",children:["• ",(x/1e3).toFixed(2),"s"]})]}),(0,t.jsx)("div",{className:"bg-white border border-red-200 rounded p-2 max-h-48 overflow-y-auto",children:(0,t.jsx)("pre",{className:"text-xs whitespace-pre-wrap text-red-700 font-mono",children:n.message})})]})]})}),a&&!l&&!n&&(0,t.jsx)("div",{className:"space-y-3",children:"formatted"===c?a.map((e,s)=>(0,t.jsxs)("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:["text"===e.type&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"bg-gray-50 px-3 py-1 border-b border-gray-200",children:(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Text Response"})}),(0,t.jsx)("div",{className:"p-3",children:(0,t.jsx)("div",{className:"bg-white rounded border border-gray-200 max-h-64 overflow-y-auto",children:(0,t.jsx)("div",{className:"p-3 space-y-2",children:e.text.split("\n\n").map((e,s)=>{if(""===e.trim())return null;if(e.startsWith("##")){let r=e.replace(/^#+\s/,"");return(0,t.jsx)("div",{className:"border-b border-gray-200 pb-1 mb-2",children:(0,t.jsx)("h3",{className:"text-sm font-semibold text-gray-900",children:r})},s)}let r=/(https?:\/\/[^\s\)]+)/g;if(r.test(e)){let l=e.split(r);return(0,t.jsx)("div",{className:"bg-blue-50 border border-blue-200 rounded p-2",children:(0,t.jsx)("div",{className:"text-xs text-gray-700 leading-relaxed whitespace-pre-wrap",children:l.map((e,s)=>r.test(e)?(0,t.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline break-all",children:e},s):e)})},s)}return e.includes("Score:")?(0,t.jsx)("div",{className:"bg-green-50 border-l-4 border-green-400 p-2 rounded-r",children:(0,t.jsx)("p",{className:"text-xs text-green-800 font-medium whitespace-pre-wrap",children:e})},s):(0,t.jsx)("div",{className:"bg-gray-50 rounded p-2 border border-gray-200",children:(0,t.jsx)("div",{className:"text-xs text-gray-700 leading-relaxed whitespace-pre-wrap font-mono",children:e})},s)}).filter(Boolean)})})})]}),"image"===e.type&&e.url&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"bg-gray-50 px-3 py-1 border-b border-gray-200",children:(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Image Response"})}),(0,t.jsx)("div",{className:"p-3",children:(0,t.jsx)("div",{className:"bg-gray-50 rounded p-3 border border-gray-200",children:(0,t.jsx)("img",{src:e.url,alt:"Tool result",className:"max-w-full h-auto rounded shadow-sm"})})})]}),"embedded_resource"===e.type&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"bg-gray-50 px-3 py-1 border-b border-gray-200",children:(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Embedded Resource"})}),(0,t.jsx)("div",{className:"p-3",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2 p-3 bg-blue-50 border border-blue-200 rounded",children:[(0,t.jsx)("div",{className:"flex-shrink-0",children:(0,t.jsx)("svg",{className:"h-5 w-5 text-blue-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsxs)("p",{className:"text-xs font-medium text-blue-900",children:["Resource Type: ",e.resource_type]}),e.url&&(0,t.jsxs)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center text-xs text-blue-600 hover:text-blue-800 hover:underline mt-1 transition-colors",children:["View Resource",(0,t.jsxs)("svg",{className:"ml-1 h-3 w-3",fill:"currentColor",viewBox:"0 0 20 20",children:[(0,t.jsx)("path",{d:"M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"}),(0,t.jsx)("path",{d:"M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"})]})]})]})]})})]})]},s)):(0,t.jsx)("div",{className:"bg-white rounded border border-gray-200",children:(0,t.jsx)("div",{className:"p-3 overflow-auto max-h-80 bg-gray-50",children:(0,t.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all text-gray-800",children:JSON.stringify(a,null,2)})})})})]})]}):(0,t.jsx)("div",{className:"flex flex-col justify-center items-center h-48 text-gray-500",children:(0,t.jsxs)("div",{className:"text-center max-w-sm",children:[(0,t.jsx)("div",{className:"mb-3",children:(0,t.jsx)("svg",{className:"mx-auto h-12 w-12 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1,d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),(0,t.jsx)("h4",{className:"text-sm font-medium text-gray-900 mb-1",children:"Ready to Call Tool"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 leading-relaxed",children:'Configure the input parameters and click "Call Tool" to see the results here.'})]})})})]})]})]})}var sw=r(69993),sZ=e=>{let{serverId:s,accessToken:r,auth_type:l,userRole:a,userID:n,serverAlias:i}=e,[o,c]=(0,f.useState)(null),[d,m]=(0,f.useState)(null),[u,x]=(0,f.useState)(null),{data:h,isLoading:p,error:g}=(0,b.a)({queryKey:["mcpTools",s],queryFn:()=>{if(!r)throw Error("Access Token required");return(0,_.listMCPTools)(r,s)},enabled:!!r,staleTime:3e4}),{mutate:j,isPending:v}=(0,e5.D)({mutationFn:async e=>{if(!r)throw Error("Access Token required");try{return await (0,_.callMCPTool)(r,s,e.tool.name,e.arguments)}catch(e){throw e}},onSuccess:e=>{m(e.content),x(null)},onError:e=>{x(e),m(null)}}),y=(null==h?void 0:h.tools)||[];return(0,t.jsx)("div",{className:"w-full h-screen p-4 bg-white",children:(0,t.jsx)(V.Zb,{className:"w-full rounded-xl shadow-md overflow-hidden",children:(0,t.jsxs)("div",{className:"flex h-auto w-full gap-4",children:[(0,t.jsxs)("div",{className:"w-1/4 p-4 bg-gray-50 flex flex-col",children:[(0,t.jsx)(V.Dx,{className:"text-xl font-semibold mb-6 mt-2",children:"MCP Tools"}),(0,t.jsx)("div",{className:"flex flex-col flex-1",children:(0,t.jsxs)("div",{className:"flex flex-col flex-1 min-h-0",children:[(0,t.jsxs)(V.xv,{className:"font-medium block mb-3 text-gray-700 flex items-center",children:[(0,t.jsx)(U.Z,{className:"mr-2"})," Available Tools",y.length>0&&(0,t.jsx)("span",{className:"ml-2 bg-blue-100 text-blue-800 text-xs font-medium px-2 py-0.5 rounded-full",children:y.length})]}),p&&(0,t.jsxs)("div",{className:"flex flex-col items-center justify-center py-8 bg-white border border-gray-200 rounded-lg",children:[(0,t.jsxs)("div",{className:"relative mb-3",children:[(0,t.jsx)("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-gray-200"}),(0,t.jsx)("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-blue-600 border-t-transparent absolute top-0"})]}),(0,t.jsx)("p",{className:"text-xs font-medium text-gray-700",children:"Loading tools..."})]}),(null==h?void 0:h.error)&&!p&&!y.length&&(0,t.jsx)("div",{className:"p-3 text-xs text-red-800 rounded-lg bg-red-50 border border-red-200",children:(0,t.jsxs)("p",{className:"font-medium",children:["Error: ",h.message]})}),!p&&!(null==h?void 0:h.error)&&(!y||0===y.length)&&(0,t.jsxs)("div",{className:"p-4 text-center bg-white border border-gray-200 rounded-lg",children:[(0,t.jsx)("div",{className:"mx-auto w-8 h-8 bg-gray-200 rounded-full flex items-center justify-center mb-2",children:(0,t.jsx)("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 8.172V5L8 4z"})})}),(0,t.jsx)("p",{className:"text-xs font-medium text-gray-700 mb-1",children:"No tools available"}),(0,t.jsx)("p",{className:"text-xs text-gray-500",children:"No tools found for this server"})]}),!p&&!(null==h?void 0:h.error)&&y.length>0&&(0,t.jsx)("div",{className:"space-y-2 flex-1 overflow-y-auto min-h-0 mcp-tools-scrollable",style:{maxHeight:"400px",scrollbarWidth:"auto",scrollbarColor:"#cbd5e0 #f7fafc"},children:y.map(e=>(0,t.jsxs)("div",{className:"border rounded-lg p-3 cursor-pointer transition-all hover:shadow-sm ".concat((null==o?void 0:o.name)===e.name?"border-blue-500 bg-blue-50 ring-1 ring-blue-200":"border-gray-200 bg-white hover:border-gray-300"),onClick:()=>{c(e),m(null),x(null)},children:[(0,t.jsxs)("div",{className:"flex items-start space-x-2",children:[e.mcp_info.logo_url&&(0,t.jsx)("img",{src:e.mcp_info.logo_url,alt:"".concat(e.mcp_info.server_name," logo"),className:"w-4 h-4 object-contain flex-shrink-0 mt-0.5"}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsx)("h4",{className:"font-mono text-xs font-medium text-gray-900 truncate",children:e.name}),(0,t.jsx)("p",{className:"text-xs text-gray-500 truncate",children:e.mcp_info.server_name}),(0,t.jsx)("p",{className:"text-xs text-gray-600 mt-1 line-clamp-2 leading-relaxed",children:e.description})]})]}),(null==o?void 0:o.name)===e.name&&(0,t.jsx)("div",{className:"mt-2 pt-2 border-t border-blue-200",children:(0,t.jsxs)("div",{className:"flex items-center text-xs font-medium text-blue-700",children:[(0,t.jsx)("svg",{className:"w-3 h-3 mr-1",fill:"currentColor",viewBox:"0 0 20 20",children:(0,t.jsx)("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),"Selected"]})})]},e.name))})]})})]}),(0,t.jsxs)("div",{className:"w-3/4 flex flex-col bg-white",children:[(0,t.jsx)("div",{className:"p-4 border-b border-gray-200 flex justify-between items-center",children:(0,t.jsx)(V.Dx,{className:"text-xl font-semibold mb-0",children:"Tool Testing Playground"})}),(0,t.jsx)("div",{className:"flex-1 overflow-auto p-4",children:o?(0,t.jsx)("div",{className:"h-full",children:(0,t.jsx)(s_,{tool:o,onSubmit:e=>{j({tool:o,arguments:e})},result:d,error:u,isLoading:v,onClose:()=>c(null)})}):(0,t.jsxs)("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[(0,t.jsx)(sw.Z,{style:{fontSize:"48px",marginBottom:"16px"}}),(0,t.jsx)(V.xv,{className:"text-lg font-medium text-gray-600 mb-2",children:"Select a Tool to Test"}),(0,t.jsx)(V.xv,{className:"text-center text-gray-500 max-w-md",children:"Choose a tool from the left sidebar to start testing its functionality with custom inputs."})]})})]})]})})})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1953-eb323beb5ad38342.js b/litellm/proxy/_experimental/out/_next/static/chunks/1953-eb323beb5ad38342.js new file mode 100644 index 00000000000..49c20f6268d --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1953-eb323beb5ad38342.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1953],{19046:function(e,t,s){s.d(t,{Dx:function(){return n.Z},Zb:function(){return r.Z},oi:function(){return o.Z},xv:function(){return l.Z},zx:function(){return a.Z}});var a=s(78489),r=s(12514),l=s(84264),o=s(49566),n=s(96761)},88712:function(e,t,s){var a=s(57437);s(2265);var r=s(33145),l=s(66830),o=s(50010);t.Z=e=>{let{message:t}=e;if(!(0,l.br)(t))return null;let s="string"==typeof t.content&&t.content.includes("[PDF attached]");return(0,a.jsx)("div",{className:"mb-2",children:s?(0,a.jsx)("div",{className:"w-64 h-32 rounded-md border border-gray-200 bg-red-50 flex items-center justify-center",children:(0,a.jsx)(o.Z,{style:{fontSize:"48px",color:"#dc2626"}})}):(0,a.jsx)(r.default,{src:t.imagePreviewUrl||"",alt:"User uploaded image",width:256,height:200,className:"max-w-64 rounded-md border border-gray-200 shadow-sm",style:{maxHeight:"200px",width:"auto",height:"auto"}})})}},27930:function(e,t,s){var a=s(57437);s(2265);var r=s(65319),l=s(99981),o=s(53508);let{Dragger:n}=r.default;t.Z=e=>{let{chatUploadedImage:t,chatImagePreviewUrl:s,onImageUpload:r,onRemoveImage:i}=e;return(0,a.jsx)(a.Fragment,{children:!t&&(0,a.jsx)(n,{beforeUpload:r,accept:"image/*,.pdf",showUploadList:!1,className:"inline-block",style:{padding:0,border:"none",background:"none"},children:(0,a.jsx)(l.Z,{title:"Attach image or PDF",children:(0,a.jsx)("button",{type:"button",className:"flex items-center justify-center w-8 h-8 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-md transition-colors",children:(0,a.jsx)(o.Z,{style:{fontSize:"16px"}})})})})})}},66830:function(e,t,s){s.d(t,{Hk:function(){return l},Sn:function(){return r},br:function(){return o}});let a=e=>new Promise((t,s)=>{let a=new FileReader;a.onload=()=>{t(a.result)},a.onerror=s,a.readAsDataURL(e)}),r=async(e,t)=>({role:"user",content:[{type:"text",text:e},{type:"image_url",image_url:{url:await a(t)}}]}),l=(e,t,s,a)=>{let r="";t&&a&&(r=a.toLowerCase().endsWith(".pdf")?"[PDF attached]":"[Image attached]");let l={role:"user",content:t?"".concat(e," ").concat(r):e};return t&&s&&(l.imagePreviewUrl=s),l},o=e=>"user"===e.role&&"string"==typeof e.content&&(e.content.includes("[Image attached]")||e.content.includes("[PDF attached]"))&&!!e.imagePreviewUrl},41953:function(e,t,s){s.d(t,{Z:function(){return ts}});var a=s(57437),r=s(61935),l=s(92403),o=s(55322),n=s(62272),i=s(26430),c=s(12660),d=s(25980),m=s(69993),u=s(71891),p=s(58630),x=s(15424),g=s(44625),h=s(57400),f=s(11894),v=s(15883),y=s(99890),b=s(26349),j=s(50010),N=s(79276),w=s(19046),S=s(4260),_=s(65319),P=s(57840),C=s(37592),k=s(5545),A=s(79326),E=s(99981),I=s(10353),Z=s(22116),T=s(2265),L=s(62831),M=s(17906),O=s(94263),R=s(93837),K=s(9309),U=s(67479),D=s(87972),B=s(10032),z=s(12221);let F=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function H(e){if(!e)return[];if(Array.isArray(e))return e.map(e=>G(e)).filter(e=>void 0!==e);let t=G(e);return void 0!==t?[t]:[]}function G(e,t){if(!e)return;let s=void 0!==t?t:e.default;if("object"===e.type){let t=F(s)?{...s}:{};return e.properties&&Object.entries(e.properties).forEach(e=>{let[s,a]=e;t[s]=G(a,t[s])}),t}if("array"===e.type){if(Array.isArray(s)){let t=e.items;if(!t)return s;if(0===s.length){let e=H(t);return e.length?e:s}return Array.isArray(t)?s.map((e,s)=>{var a;return G(null!==(a=t[s])&&void 0!==a?a:t[t.length-1],e)}):s.map(e=>G(t,e))}return void 0!==s?s:H(e.items)}if(void 0!==s)return s;switch(e.type){case"integer":case"number":return 0;case"boolean":return!1;default:return""}}let q=e=>{let t=G(e);if("object"===e.type||"array"===e.type){let s="array"===e.type?[]:{};return JSON.stringify(null!=t?t:s,null,2)}return t},J=(0,T.forwardRef)((e,t)=>{let{tool:s,className:r}=e,[l]=B.Z.useForm(),o=(0,T.useMemo)(()=>"string"==typeof s.inputSchema?{type:"object",properties:{input:{type:"string",description:"Input for this tool"}},required:["input"]}:s.inputSchema,[s.inputSchema]),n=(0,T.useMemo)(()=>{var e,t;return(null===(t=o.properties)||void 0===t?void 0:null===(e=t.params)||void 0===e?void 0:e.type)==="object"&&o.properties.params.properties?{type:"object",properties:o.properties.params.properties,required:o.properties.params.required||[]}:o},[o]);return((0,T.useImperativeHandle)(t,()=>({getSubmitValues:async()=>(function(e,t,s){var a,r;let l={};return Object.entries(e).forEach(e=>{var s;let[a,r]=e,o=null===(s=t.properties)||void 0===s?void 0:s[a];if(o&&null!=r&&""!==r)switch(o.type){case"boolean":l[a]="true"===r||!0===r;break;case"number":case"integer":{let e=Number(r);l[a]=Number.isNaN(e)?r:"integer"===o.type?Math.trunc(e):e;break}case"object":case"array":try{let e="string"==typeof r?JSON.parse(r):r,t="object"===o.type&&null!==e&&"object"==typeof e&&!Array.isArray(e),s="array"===o.type&&Array.isArray(e);"object"===o.type&&t||"array"===o.type&&s?l[a]=e:l[a]=r}catch(e){l[a]=r}break;case"string":l[a]=String(r);break;default:l[a]=r}else null!=r&&""!==r&&(l[a]=r)}),(null===(r=s.properties)||void 0===r?void 0:null===(a=r.params)||void 0===a?void 0:a.type)==="object"&&s.properties.params.properties?{params:l}:l})(await l.validateFields(),n,o)})),T.useEffect(()=>{if(l.resetFields(),!n.properties)return;let e={};Object.entries(n.properties).forEach(t=>{let[s,a]=t;e[s]=q(a)}),l.setFieldsValue(e)},[l,n,s]),"string"==typeof s.inputSchema)?(0,a.jsx)(B.Z,{form:l,layout:"vertical",className:r,children:(0,a.jsx)(B.Z.Item,{label:(0,a.jsxs)("span",{className:"text-sm font-medium text-gray-700",children:["Input ",(0,a.jsx)("span",{className:"text-red-500",children:"*"})]}),name:"input",rules:[{required:!0,message:"Please enter input for this tool"}],children:(0,a.jsx)(S.default,{placeholder:"Enter input for this tool"})})}):n.properties?(0,a.jsx)(B.Z,{form:l,layout:"vertical",className:r,children:Object.entries(n.properties).map(e=>{var t,r,l,o;let[i,c]=e,d=q(c),m="".concat(s.name,"-").concat(i);return(0,a.jsx)(B.Z.Item,{label:(0,a.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:[i," ",(null===(t=n.required)||void 0===t?void 0:t.includes(i))&&(0,a.jsx)("span",{className:"text-red-500",children:"*"}),c.description&&(0,a.jsx)(E.Z,{title:c.description,children:(0,a.jsx)(x.Z,{className:"ml-2 text-gray-400 hover:text-gray-600"})})]}),name:i,initialValue:d,rules:[{required:null===(r=n.required)||void 0===r?void 0:r.includes(i),message:"Please enter ".concat(i)},..."object"===c.type||"array"===c.type?[{validator:(e,t)=>{var s;if((null==t||""===t)&&!(null===(s=n.required)||void 0===s?void 0:s.includes(i)))return Promise.resolve();try{let e="string"==typeof t?JSON.parse(t):t,s="object"===c.type&&null!==e&&"object"==typeof e&&!Array.isArray(e),a="array"===c.type&&Array.isArray(e);if("object"===c.type&&s||"array"===c.type&&a)return Promise.resolve();return Promise.reject(Error("object"===c.type?"Please enter a JSON object":"Please enter a JSON array"))}catch(e){return Promise.reject(Error("Invalid JSON"))}}}]:[]],children:"string"===c.type&&c.enum?(0,a.jsx)(C.default,{placeholder:"Select ".concat(i),allowClear:!(null===(l=n.required)||void 0===l?void 0:l.includes(i)),options:c.enum.map(e=>({value:e,label:e}))}):"string"!==c.type||c.enum?"number"===c.type||"integer"===c.type?(0,a.jsx)(z.Z,{step:"integer"===c.type?1:void 0,placeholder:c.description||"Enter ".concat(i),className:"w-full",style:{width:"100%"}}):"boolean"===c.type?(0,a.jsx)(C.default,{placeholder:"Select ".concat(i),allowClear:!(null===(o=n.required)||void 0===o?void 0:o.includes(i)),options:[{value:!0,label:"True"},{value:!1,label:"False"}]}):"object"===c.type||"array"===c.type?(0,a.jsx)(S.default.TextArea,{rows:"object"===c.type?4:3,placeholder:c.description||("object"===c.type?"Enter JSON object for ".concat(i):"Enter JSON array for ".concat(i)),spellCheck:!1,className:"font-mono"}):(0,a.jsx)(S.default,{placeholder:c.description||"Enter ".concat(i),allowClear:!0}):(0,a.jsx)(S.default,{placeholder:c.description||"Enter ".concat(i),allowClear:!0})},m)})}):(0,a.jsx)(B.Z,{form:l,layout:"vertical",className:r,children:(0,a.jsx)("div",{className:"py-4 text-center text-sm text-gray-500",children:"No parameters required for this tool."})})});J.displayName="MCPToolArgumentsForm";var W=s(9114),V=s(19250),Y=s(99020),X=s(97415),$=s(26832),Q=s(85498);async function ee(e,t,s,a){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],l=arguments.length>5?arguments[5]:void 0,o=arguments.length>6?arguments[6]:void 0,n=arguments.length>7?arguments[7]:void 0,i=arguments.length>8?arguments[8]:void 0,c=arguments.length>9?arguments[9]:void 0,d=arguments.length>10?arguments[10]:void 0,m=arguments.length>11?arguments[11]:void 0,u=arguments.length>12?arguments[12]:void 0,p=(arguments.length>13&&arguments[13],arguments.length>14?arguments[14]:void 0);if(!a)throw Error("Virtual Key is required");console.log=function(){};let x=p||(0,V.getProxyBaseUrl)(),g={};r&&r.length>0&&(g["x-litellm-tags"]=r.join(","));let h=new Q.ZP({apiKey:a,baseURL:x,dangerouslyAllowBrowser:!0,defaultHeaders:g});try{let a=Date.now(),r=!1,p={model:s,messages:e.map(e=>({role:e.role,content:e.content})),stream:!0,max_tokens:1024,litellm_trace_id:c};for await(let e of(d&&(p.vector_store_ids=d),m&&(p.guardrails=m),u&&(p.policies=u),h.messages.stream(p,{signal:l}))){if(console.log("Stream event:",e),"content_block_delta"===e.type){let l=e.delta;if(!r){r=!0;let e=Date.now()-a;console.log("First token received! Time:",e,"ms"),n&&n(e)}"text_delta"===l.type?t("assistant",l.text,s):"reasoning_delta"===l.type&&o&&o(l.text)}if("message_delta"===e.type&&e.usage&&i){let t=e.usage;console.log("Usage data found:",t);let s={completionTokens:t.output_tokens,promptTokens:t.input_tokens,totalTokens:t.input_tokens+t.output_tokens};i(s)}}}catch(e){throw(null==l?void 0:l.aborted)?console.log("Anthropic messages request was cancelled"):W.ZP.fromBackend("Error occurred while generating model response. Please try again. Error: ".concat(e)),e}}var et=s(7271);async function es(e,t,s,a,r,l,o,n,i,c){console.log=function(){},console.log("isLocal:",!1);let d=c||(0,V.getProxyBaseUrl)(),m=new et.ZP.OpenAI({apiKey:r,baseURL:d,dangerouslyAllowBrowser:!0,defaultHeaders:l&&l.length>0?{"x-litellm-tags":l.join(",")}:void 0});try{let r=await m.audio.speech.create({model:a,input:e,voice:t,...n?{response_format:n}:{},...i?{speed:i}:{}},{signal:o}),l=await r.blob(),c=URL.createObjectURL(l);s(c,a)}catch(e){throw(null==o?void 0:o.aborted)?console.log("Audio speech request was cancelled"):W.ZP.fromBackend("Error occurred while generating speech. Please try again. Error: ".concat(e)),e}}async function ea(e,t,s,a,r,l,o,n,i,c,d){console.log=function(){},console.log("isLocal:",!1);let m=d||(0,V.getProxyBaseUrl)(),u=new et.ZP.OpenAI({apiKey:a,baseURL:m,dangerouslyAllowBrowser:!0,defaultHeaders:r&&r.length>0?{"x-litellm-tags":r.join(",")}:void 0});try{console.log("Processing audio file for transcription:",e.name);let a=await u.audio.transcriptions.create({model:s,file:e,...o?{language:o}:{},...n?{prompt:n}:{},...i?{response_format:i}:{},...void 0!==c?{temperature:c}:{}},{signal:l});if(console.log("Transcription response:",a),a&&a.text)t(a.text,s),W.ZP.success("Audio transcribed successfully");else throw Error("No transcription text in response")}catch(e){if(console.error("Error making audio transcription request:",e),null==l?void 0:l.aborted)console.log("Audio transcription request was cancelled");else{var p;let t="Failed to transcribe audio";(null==e?void 0:null===(p=e.error)||void 0===p?void 0:p.message)?t=e.error.message:(null==e?void 0:e.message)&&(t=e.message),W.ZP.fromBackend("Audio transcription failed: ".concat(t))}throw e}}var er=s(95459);async function el(e,t,s,a,r,l){if(!a)throw Error("Virtual Key is required");console.log=function(){};let o=l||(0,V.getProxyBaseUrl)(),n={};r&&r.length>0&&(n["x-litellm-tags"]=r.join(","));try{var i,c,d;let r=o.endsWith("/")?o.slice(0,-1):o,l=await fetch("".concat(r,"/embeddings"),{method:"POST",headers:{"Content-Type":"application/json",[(0,V.getGlobalLitellmHeaderName)()]:"Bearer ".concat(a),...n},body:JSON.stringify({model:s,input:e})});if(!l.ok){let e=await l.text();throw Error(e||"Request failed with status ".concat(l.status))}let m=await l.json(),u=null==m?void 0:null===(c=m.data)||void 0===c?void 0:null===(i=c[0])||void 0===i?void 0:i.embedding;if(!u)throw Error("No embedding returned from server");t(JSON.stringify(u),null!==(d=null==m?void 0:m.model)&&void 0!==d?d:s)}catch(e){throw W.ZP.fromBackend("Error occurred while making embeddings request. Please try again. Error: ".concat(e)),e}}var eo=s(91643),en=s(10703);async function ei(e,t,s,a,r,l,o,n){console.log=function(){},console.log("isLocal:",!1);let i=n||(0,V.getProxyBaseUrl)(),c=new et.ZP.OpenAI({apiKey:r,baseURL:i,dangerouslyAllowBrowser:!0,defaultHeaders:l&&l.length>0?{"x-litellm-tags":l.join(",")}:void 0});try{let r=Array.isArray(e)?e:[e],l=[];for(let e=0;e1&&W.ZP.success("Successfully processed ".concat(l.length," images"))}catch(e){if(console.error("Error making image edit request:",e),null==o?void 0:o.aborted)console.log("Image edits request was cancelled");else{var d;let t="Failed to edit image(s)";(null==e?void 0:null===(d=e.error)||void 0===d?void 0:d.message)?t=e.error.message:(null==e?void 0:e.message)&&(t=e.message),W.ZP.fromBackend("Image edit failed: ".concat(t))}throw e}}async function ec(e,t,s,a,r,l,o){console.log=function(){},console.log("isLocal:",!1);let n=o||(0,V.getProxyBaseUrl)(),i=new et.ZP.OpenAI({apiKey:a,baseURL:n,dangerouslyAllowBrowser:!0,defaultHeaders:r&&r.length>0?{"x-litellm-tags":r.join(",")}:void 0});try{let a=await i.images.generate({model:s,prompt:e},{signal:l});if(console.log(a.data),a.data&&a.data[0]){if(a.data[0].url)t(a.data[0].url,s);else if(a.data[0].b64_json){let e=a.data[0].b64_json;t("data:image/png;base64,".concat(e),s)}else throw Error("No image data found in response")}else throw Error("Invalid response format")}catch(e){throw(null==l?void 0:l.aborted)?console.log("Image generation request was cancelled"):W.ZP.fromBackend("Error occurred while generating image. Please try again. Error: ".concat(e)),e}}async function ed(e,t,s,a){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],l=arguments.length>5?arguments[5]:void 0,o=arguments.length>6?arguments[6]:void 0,n=arguments.length>7?arguments[7]:void 0,i=arguments.length>8?arguments[8]:void 0,c=arguments.length>9?arguments[9]:void 0,d=arguments.length>10?arguments[10]:void 0,m=arguments.length>11?arguments[11]:void 0,u=arguments.length>12?arguments[12]:void 0,p=arguments.length>13?arguments[13]:void 0,x=arguments.length>14?arguments[14]:void 0,g=arguments.length>15?arguments[15]:void 0,h=arguments.length>16?arguments[16]:void 0,f=arguments.length>17?arguments[17]:void 0,v=arguments.length>18?arguments[18]:void 0,y=arguments.length>19?arguments[19]:void 0,b=arguments.length>20?arguments[20]:void 0,j=arguments.length>21?arguments[21]:void 0;if(!a)throw Error("Virtual Key is required");if(!s||""===s.trim())throw Error("Model is required. Please select a model before sending a request.");console.log=function(){};let N=y||(0,V.getProxyBaseUrl)(),w={};r&&r.length>0&&(w["x-litellm-tags"]=r.join(","));let S=new et.ZP.OpenAI({apiKey:a,baseURL:N,dangerouslyAllowBrowser:!0,defaultHeaders:w});try{let a=Date.now(),r=!1,y=e.map(e=>(Array.isArray(e.content),{role:e.role,content:e.content,type:"message"})),N=[];p&&p.length>0&&(p.includes("__all__")?N.push({type:"mcp",server_label:"litellm",server_url:"litellm_proxy/mcp",require_approval:"never"}):p.forEach(e=>{let t=null==b?void 0:b.find(t=>t.server_id===e),s=(null==t?void 0:t.alias)||(null==t?void 0:t.server_name)||e,a=(null==j?void 0:j[e])||[];N.push({type:"mcp",server_label:"litellm",server_url:"litellm_proxy/mcp/".concat(s),require_approval:"never",...a.length>0?{allowed_tools:a}:{}})})),f&&N.push({type:"code_interpreter",container:{type:"auto"}});let w=await S.responses.create({model:s,input:y,stream:!0,litellm_trace_id:c,...x?{previous_response_id:x}:{},...d?{vector_store_ids:d}:{},...m?{guardrails:m}:{},...u?{policies:u}:{},...N.length>0?{tools:N,tool_choice:"auto"}:{}},{signal:l}),Z="",T={code:"",containerId:""};for await(let e of w)if(console.log("Response event:",e),"object"==typeof e&&null!==e){var _,P,C,k,A,E,I;if(((null===(_=e.type)||void 0===_?void 0:_.startsWith("response.mcp_"))||"response.output_item.done"===e.type&&((null===(P=e.item)||void 0===P?void 0:P.type)==="mcp_list_tools"||(null===(C=e.item)||void 0===C?void 0:C.type)==="mcp_call"))&&(console.log("MCP event received:",e),h)){let t={type:e.type,sequence_number:e.sequence_number,output_index:e.output_index,item_id:e.item_id||(null===(E=e.item)||void 0===E?void 0:E.id),item:e.item,delta:e.delta,arguments:e.arguments,timestamp:Date.now()};h(t)}if("response.output_item.done"===e.type&&(null===(k=e.item)||void 0===k?void 0:k.type)==="mcp_call"&&(null===(A=e.item)||void 0===A?void 0:A.name)&&(Z=e.item.name,console.log("MCP tool used:",Z)),T=function(e,t){var s;return"response.output_item.done"===e.type&&(null===(s=e.item)||void 0===s?void 0:s.type)==="code_interpreter_call"?(console.log("Code interpreter call completed:",e.item),{code:e.item.code||"",containerId:e.item.container_id||""}):t}(e,T),!function(e,t,s){var a,r;if("response.output_item.done"===e.type&&(null===(a=e.item)||void 0===a?void 0:a.type)==="message"&&(null===(r=e.item)||void 0===r?void 0:r.content)&&s){for(let a of e.item.content)if("output_text"===a.type&&a.annotations){let e=a.annotations.filter(e=>"container_file_citation"===e.type);(e.length>0||t.code)&&s({code:t.code,containerId:t.containerId,annotations:e})}}}(e,T,v),"response.role.delta"===e.type)continue;if("response.output_text.delta"===e.type&&"string"==typeof e.delta){let l=e.delta;if(console.log("Text delta",l),l.trim().length>0&&(t("assistant",l,s),!r)){r=!0;let e=Date.now()-a;console.log("First token received! Time:",e,"ms"),n&&n(e)}}if("response.reasoning.delta"===e.type&&"delta"in e){let t=e.delta;"string"==typeof t&&o&&o(t)}if("response.completed"===e.type&&"response"in e){let t=e.response,s=t.usage;if(console.log("Usage data:",s),console.log("Response completed event:",t),t.id&&g&&(console.log("Response ID for session management:",t.id),g(t.id)),s&&i){console.log("Usage data:",s);let e={completionTokens:s.output_tokens,promptTokens:s.input_tokens,totalTokens:s.total_tokens};(null===(I=s.completion_tokens_details)||void 0===I?void 0:I.reasoning_tokens)&&(e.reasoningTokens=s.completion_tokens_details.reasoning_tokens),i(e,Z)}}}return w}catch(e){throw(null==l?void 0:l.aborted)?console.log("Responses API request was cancelled"):W.ZP.fromBackend("Error occurred while generating model response. Please try again. Error: ".concat(e)),e}}var em=s(83669),eu=s(29271),ep=s(5540),ex=s(38434),eg=s(23639),eh=s(70464),ef=s(77565);let ev=e=>{switch(e){case"completed":return(0,a.jsx)(em.Z,{className:"text-green-500"});case"working":case"submitted":return(0,a.jsx)(r.Z,{className:"text-blue-500"});case"failed":case"canceled":return(0,a.jsx)(eu.Z,{className:"text-red-500"});default:return(0,a.jsx)(ep.Z,{className:"text-gray-500"})}},ey=e=>{switch(e){case"completed":return"bg-green-100 text-green-700";case"working":case"submitted":return"bg-blue-100 text-blue-700";case"failed":case"canceled":return"bg-red-100 text-red-700";default:return"bg-gray-100 text-gray-700"}},eb=e=>{if(!e)return null;try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch(t){return e}},ej=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return e?e.length>t?"".concat(e.substring(0,t),"…"):e:null},eN=e=>{navigator.clipboard.writeText(e)};var ew=e=>{let{a2aMetadata:t,timeToFirstToken:s,totalLatency:r}=e,[l,o]=(0,T.useState)(!1);if(!t&&!s&&!r)return null;let{taskId:i,contextId:c,status:d,metadata:u}=t||{},p=eb(null==d?void 0:d.timestamp);return(0,a.jsxs)("div",{className:"a2a-metrics mt-3 pt-2 border-t border-gray-200 text-xs",children:[(0,a.jsxs)("div",{className:"flex items-center mb-2 text-gray-600",children:[(0,a.jsx)(m.Z,{className:"mr-1.5 text-blue-500"}),(0,a.jsx)("span",{className:"font-medium text-gray-700",children:"A2A Metadata"})]}),(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-gray-500 ml-4",children:[(null==d?void 0:d.state)&&(0,a.jsxs)("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ".concat(ey(d.state)),children:[ev(d.state),(0,a.jsx)("span",{className:"ml-1 capitalize",children:d.state})]}),p&&(0,a.jsx)(E.Z,{title:null==d?void 0:d.timestamp,children:(0,a.jsxs)("span",{className:"flex items-center",children:[(0,a.jsx)(ep.Z,{className:"mr-1"}),p]})}),void 0!==r&&(0,a.jsx)(E.Z,{title:"Total latency",children:(0,a.jsxs)("span",{className:"flex items-center text-blue-600",children:[(0,a.jsx)(ep.Z,{className:"mr-1"}),(r/1e3).toFixed(2),"s"]})}),void 0!==s&&(0,a.jsx)(E.Z,{title:"Time to first token",children:(0,a.jsxs)("span",{className:"flex items-center text-green-600",children:["TTFT: ",(s/1e3).toFixed(2),"s"]})})]}),(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-3 text-gray-500 ml-4 mt-1.5",children:[i&&(0,a.jsx)(E.Z,{title:"Click to copy: ".concat(i),children:(0,a.jsxs)("span",{className:"flex items-center cursor-pointer hover:text-gray-700",onClick:()=>eN(i),children:[(0,a.jsx)(ex.Z,{className:"mr-1"}),"Task: ",ej(i),(0,a.jsx)(eg.Z,{className:"ml-1 text-gray-400 hover:text-gray-600"})]})}),c&&(0,a.jsx)(E.Z,{title:"Click to copy: ".concat(c),children:(0,a.jsxs)("span",{className:"flex items-center cursor-pointer hover:text-gray-700",onClick:()=>eN(c),children:[(0,a.jsx)(n.Z,{className:"mr-1"}),"Session: ",ej(c),(0,a.jsx)(eg.Z,{className:"ml-1 text-gray-400 hover:text-gray-600"})]})}),(u||(null==d?void 0:d.message))&&(0,a.jsxs)(k.ZP,{type:"text",size:"small",className:"text-xs text-blue-500 hover:text-blue-700 p-0 h-auto",onClick:()=>o(!l),children:[l?(0,a.jsx)(eh.Z,{}):(0,a.jsx)(ef.Z,{}),(0,a.jsx)("span",{className:"ml-1",children:"Details"})]})]}),l&&(0,a.jsxs)("div",{className:"mt-2 ml-4 p-3 bg-gray-50 rounded-md text-gray-600 border border-gray-200",children:[(null==d?void 0:d.message)&&(0,a.jsxs)("div",{className:"mb-2",children:[(0,a.jsx)("span",{className:"font-medium text-gray-700",children:"Status Message:"}),(0,a.jsx)("span",{className:"ml-2",children:d.message})]}),i&&(0,a.jsxs)("div",{className:"mb-1.5 flex items-center",children:[(0,a.jsx)("span",{className:"font-medium text-gray-700 w-24",children:"Task ID:"}),(0,a.jsx)("code",{className:"ml-2 px-2 py-1 bg-white border border-gray-200 rounded text-xs font-mono",children:i}),(0,a.jsx)(eg.Z,{className:"ml-2 cursor-pointer text-gray-400 hover:text-blue-500",onClick:()=>eN(i)})]}),c&&(0,a.jsxs)("div",{className:"mb-1.5 flex items-center",children:[(0,a.jsx)("span",{className:"font-medium text-gray-700 w-24",children:"Session ID:"}),(0,a.jsx)("code",{className:"ml-2 px-2 py-1 bg-white border border-gray-200 rounded text-xs font-mono",children:c}),(0,a.jsx)(eg.Z,{className:"ml-2 cursor-pointer text-gray-400 hover:text-blue-500",onClick:()=>eN(c)})]}),u&&Object.keys(u).length>0&&(0,a.jsxs)("div",{className:"mt-3",children:[(0,a.jsx)("span",{className:"font-medium text-gray-700",children:"Custom Metadata:"}),(0,a.jsx)("pre",{className:"mt-1.5 p-2 bg-white border border-gray-200 rounded text-xs font-mono overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(u,null,2)})]})]})]})},eS=s(92280),e_=s(4156),eP=s(85847),eC=e=>{let{temperature:t=1,maxTokens:s=2048,useAdvancedParams:r,onTemperatureChange:l,onMaxTokensChange:o,onUseAdvancedParamsChange:n}=e,[i,c]=(0,T.useState)(!1),d=void 0!==r?r:i,[m,u]=(0,T.useState)(t),[p,g]=(0,T.useState)(s);(0,T.useEffect)(()=>{u(t)},[t]),(0,T.useEffect)(()=>{g(s)},[s]);let h=e=>{let t=null!=e?e:1;u(t),null==l||l(t)},f=e=>{let t=null!=e?e:1e3;g(t),null==o||o(t)},v=d?"text-gray-700":"text-gray-400",y=e=>{n?n(e):c(e)};return(0,a.jsxs)("div",{className:"space-y-4 p-4 w-80",children:[(0,a.jsx)(e_.Z,{checked:d,onChange:e=>y(e.target.checked),children:(0,a.jsx)("span",{className:"font-medium",children:"Use Advanced Parameters"})}),(0,a.jsxs)("div",{className:"space-y-4 transition-opacity duration-200",style:{opacity:d?1:.4},children:[(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)(eS.x,{className:"text-sm ".concat(v),children:"Temperature"}),(0,a.jsx)(E.Z,{title:"Controls randomness. Lower values make output more deterministic, higher values more creative.",children:(0,a.jsx)(x.Z,{className:"text-xs ".concat(v," cursor-help")})})]}),(0,a.jsx)(z.Z,{min:0,max:2,step:.1,value:m,onChange:h,disabled:!d,precision:1,className:"w-20"})]}),(0,a.jsx)(eP.Z,{min:0,max:2,step:.1,value:m,onChange:h,disabled:!d,marks:{0:"0",1:"1.0",2:"2.0"}})]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)(eS.x,{className:"text-sm ".concat(v),children:"Max Tokens"}),(0,a.jsx)(E.Z,{title:"Maximum number of tokens to generate in the response.",children:(0,a.jsx)(x.Z,{className:"text-xs ".concat(v," cursor-help")})})]}),(0,a.jsx)(z.Z,{min:1,max:32768,step:1,value:p,onChange:f,disabled:!d})]}),(0,a.jsx)(eP.Z,{min:1,max:32768,step:1,value:p,onChange:f,disabled:!d,marks:{1:"1",32768:"32768"}})]})]})]})},ek=e=>{let{message:t}=e;return t.isAudio&&"string"==typeof t.content?(0,a.jsx)("div",{className:"mb-2",children:(0,a.jsx)("audio",{controls:!0,src:t.content,className:"max-w-full",style:{maxWidth:"500px"},children:"Your browser does not support the audio element."})}):null},eA=s(8443);let eE={ALLOY:"Alloy - Professional and confident",ASH:"Ash - Casual and relaxed",BALAD:"Ballad - Smooth and melodic",CORAL:"Coral - Warm and engaging",ECHO:"Echo - Friendly and conversational",FABLE:"Fable - Wise and measured",NOVA:"Nova - Friendly and conversational",ONYX:"Onyx - Deep and authoritative",SAGE:"Sage - Wise and measured",SHIMMER:"Shimmer - Bright and cheerful"},eI=Object.entries({ALLOY:"alloy",ASH:"ash",BALAD:"ballad",CORAL:"coral",ECHO:"echo",FABLE:"fable",NOVA:"nova",ONYX:"onyx",SAGE:"sage",SHIMMER:"shimmer"}).map(e=>{let[t,s]=e;return{value:s,label:eE[t]}}),eZ=[{value:eA.KP.CHAT,label:"/v1/chat/completions"},{value:eA.KP.RESPONSES,label:"/v1/responses"},{value:eA.KP.ANTHROPIC_MESSAGES,label:"/v1/messages"},{value:eA.KP.IMAGE,label:"/v1/images/generations"},{value:eA.KP.IMAGE_EDITS,label:"/v1/images/edits"},{value:eA.KP.EMBEDDINGS,label:"/v1/embeddings"},{value:eA.KP.SPEECH,label:"/v1/audio/speech"},{value:eA.KP.TRANSCRIPTION,label:"/v1/audio/transcriptions"},{value:eA.KP.A2A_AGENTS,label:"/v1/a2a/message/send"},{value:eA.KP.MCP,label:"/mcp-rest/tools/call"}];var eT=s(88712),eL=s(27930),eM=s(66830),eO=s(44851),eR=s(41589),eK=s(73879),eU=e=>{let{code:t,containerId:s,annotations:l=[],accessToken:o}=e,[n,i]=(0,T.useState)({}),[c,d]=(0,T.useState)({}),m=(0,V.getProxyBaseUrl)();(0,T.useEffect)(()=>{let e=async()=>{for(let r of l){var e,t,s,a;if(((null===(e=r.filename)||void 0===e?void 0:e.toLowerCase().endsWith(".png"))||(null===(t=r.filename)||void 0===t?void 0:t.toLowerCase().endsWith(".jpg"))||(null===(s=r.filename)||void 0===s?void 0:s.toLowerCase().endsWith(".jpeg"))||(null===(a=r.filename)||void 0===a?void 0:a.toLowerCase().endsWith(".gif")))&&r.container_id&&r.file_id){d(e=>({...e,[r.file_id]:!0}));try{let e=await fetch("".concat(m,"/v1/containers/").concat(r.container_id,"/files/").concat(r.file_id,"/content"),{headers:{[(0,V.getGlobalLitellmHeaderName)()]:"Bearer ".concat(o)}});if(e.ok){let t=await e.blob(),s=URL.createObjectURL(t);i(e=>({...e,[r.file_id]:s}))}}catch(e){console.error("Error fetching image:",e)}finally{d(e=>({...e,[r.file_id]:!1}))}}}};return l.length>0&&o&&e(),()=>{Object.values(n).forEach(e=>URL.revokeObjectURL(e))}},[l,o,m]);let u=async e=>{try{let t=await fetch("".concat(m,"/v1/containers/").concat(e.container_id,"/files/").concat(e.file_id,"/content"),{headers:{[(0,V.getGlobalLitellmHeaderName)()]:"Bearer ".concat(o)}});if(t.ok){let s=await t.blob(),a=URL.createObjectURL(s),r=document.createElement("a");r.href=a,r.download=e.filename||"file_".concat(e.file_id),document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(a)}}catch(e){console.error("Error downloading file:",e)}},p=l.filter(e=>{var t,s,a,r;return(null===(t=e.filename)||void 0===t?void 0:t.toLowerCase().endsWith(".png"))||(null===(s=e.filename)||void 0===s?void 0:s.toLowerCase().endsWith(".jpg"))||(null===(a=e.filename)||void 0===a?void 0:a.toLowerCase().endsWith(".jpeg"))||(null===(r=e.filename)||void 0===r?void 0:r.toLowerCase().endsWith(".gif"))}),x=l.filter(e=>{var t,s,a,r;return!(null===(t=e.filename)||void 0===t?void 0:t.toLowerCase().endsWith(".png"))&&!(null===(s=e.filename)||void 0===s?void 0:s.toLowerCase().endsWith(".jpg"))&&!(null===(a=e.filename)||void 0===a?void 0:a.toLowerCase().endsWith(".jpeg"))&&!(null===(r=e.filename)||void 0===r?void 0:r.toLowerCase().endsWith(".gif"))});return t||0!==l.length?(0,a.jsxs)("div",{className:"mt-3 space-y-3",children:[t&&(0,a.jsx)(eO.default,{size:"small",items:[{key:"code",label:(0,a.jsxs)("span",{className:"flex items-center gap-2 text-sm text-gray-600",children:[(0,a.jsx)(f.Z,{})," Python Code Executed"]}),children:(0,a.jsx)(M.Z,{language:"python",style:O.Z,customStyle:{margin:0,borderRadius:"6px",fontSize:"12px",maxHeight:"300px",overflow:"auto"},children:t})}]}),p.map(e=>(0,a.jsx)("div",{className:"rounded-lg border border-gray-200 overflow-hidden",children:c[e.file_id]?(0,a.jsxs)("div",{className:"flex items-center justify-center p-8 bg-gray-50",children:[(0,a.jsx)(I.Z,{indicator:(0,a.jsx)(r.Z,{spin:!0})}),(0,a.jsx)("span",{className:"ml-2 text-sm text-gray-500",children:"Loading image..."})]}):n[e.file_id]?(0,a.jsxs)("div",{children:[(0,a.jsx)("img",{src:n[e.file_id],alt:e.filename||"Generated chart",className:"max-w-full",style:{maxHeight:"400px"}}),(0,a.jsxs)("div",{className:"flex items-center justify-between px-3 py-2 bg-gray-50 border-t border-gray-200",children:[(0,a.jsxs)("span",{className:"text-xs text-gray-500 flex items-center gap-1",children:[(0,a.jsx)(eR.Z,{})," ",e.filename]}),(0,a.jsxs)("button",{onClick:()=>u(e),className:"text-xs text-blue-500 hover:text-blue-700 flex items-center gap-1",children:[(0,a.jsx)(eK.Z,{})," Download"]})]})]}):(0,a.jsx)("div",{className:"flex items-center justify-center p-4 bg-gray-50",children:(0,a.jsx)("span",{className:"text-sm text-gray-400",children:"Image not available"})})},e.file_id)),x.length>0&&(0,a.jsx)("div",{className:"flex flex-wrap gap-2",children:x.map(e=>(0,a.jsxs)("button",{onClick:()=>u(e),className:"flex items-center gap-2 px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg hover:bg-gray-100 transition-colors",children:[(0,a.jsx)(ex.Z,{className:"text-blue-500"}),(0,a.jsx)("span",{className:"text-sm",children:e.filename}),(0,a.jsx)(eK.Z,{className:"text-gray-400"})]},e.file_id))})]}):null},eD=s(42264),eB=s(63709);let ez=e=>{if(!e)return!1;let t=e.toLowerCase();return t.startsWith("openai/")||t.startsWith("gpt-")||t.startsWith("o1")||t.startsWith("o3")||t.includes("openai")};var eF=e=>{let{enabled:t,onEnabledChange:s,selectedModel:r,disabled:l=!1}=e,o=ez(r);return(0,a.jsxs)("div",{className:"border border-gray-200 rounded-lg p-3 bg-gradient-to-r from-blue-50 to-purple-50",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(f.Z,{className:"text-blue-500"}),(0,a.jsx)(eS.x,{className:"font-medium text-gray-700",children:"Code Interpreter"}),(0,a.jsx)(E.Z,{title:"Run Python code to generate files, charts, and analyze data. Container is created automatically.",children:(0,a.jsx)(x.Z,{className:"text-gray-400 text-xs"})})]}),(0,a.jsx)(eB.Z,{checked:t&&o,onChange:e=>{if(e&&!o){eD.ZP.warning("Code Interpreter is only available for OpenAI models");return}s(e)},disabled:l||!o,size:"small",className:t&&o?"bg-blue-500":""})]}),!o&&(0,a.jsx)("div",{className:"mt-2 pt-2 border-t border-gray-200",children:(0,a.jsxs)("div",{className:"flex items-start gap-2",children:[(0,a.jsx)(eu.Z,{className:"text-amber-500 mt-0.5"}),(0,a.jsxs)("div",{className:"text-xs text-gray-600",children:[(0,a.jsx)("span",{children:"Code Interpreter is currently only supported for OpenAI models. "}),(0,a.jsx)("a",{href:"https://github.com/BerriAI/litellm/issues/new?template=feature_request.yml",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"Request support for other providers"})]})]})})]})},eH=s(82971),eG=e=>{let{endpointType:t,onEndpointChange:s,className:r}=e;return(0,a.jsx)("div",{className:r,children:(0,a.jsx)(C.default,{showSearch:!0,value:t,style:{width:"100%"},onChange:s,options:eZ,className:"rounded-md",filterOption:(e,t)=>{var s,a;return(null!==(s=null==t?void 0:t.label)&&void 0!==s?s:"").toLowerCase().includes(e.toLowerCase())||(null!==(a=null==t?void 0:t.value)&&void 0!==a?a:"").toLowerCase().includes(e.toLowerCase())}})})},eq=s(29),eJ=s.n(eq);let{Text:eW}=P.default,{Panel:eV}=eO.default;var eY=e=>{var t,s;let{events:r,className:l}=e;if(console.log("MCPEventsDisplay: Received events:",r),!r||0===r.length)return console.log("MCPEventsDisplay: No events, returning null"),null;let o=r.find(e=>{var t;return"response.output_item.done"===e.type&&(null===(t=e.item)||void 0===t?void 0:t.type)==="mcp_list_tools"&&e.item.tools&&e.item.tools.length>0}),n=r.filter(e=>{var t;return"response.output_item.done"===e.type&&(null===(t=e.item)||void 0===t?void 0:t.type)==="mcp_call"});return(console.log("MCPEventsDisplay: toolsEvent:",o),console.log("MCPEventsDisplay: mcpCallEvents:",n),o||0!==n.length)?(0,a.jsxs)("div",{className:"jsx-32b14b04f420f3ac "+"mcp-events-display ".concat(l||""),children:[(0,a.jsx)(eJ(),{id:"32b14b04f420f3ac",children:'.openai-mcp-tools.jsx-32b14b04f420f3ac{position:relative;margin:0;padding:0}.openai-mcp-tools.jsx-32b14b04f420f3ac .ant-collapse.jsx-32b14b04f420f3ac{background:transparent!important;border:none!important}.openai-mcp-tools.jsx-32b14b04f420f3ac .ant-collapse-item.jsx-32b14b04f420f3ac{border:none!important;background:transparent!important}.openai-mcp-tools.jsx-32b14b04f420f3ac .ant-collapse-header.jsx-32b14b04f420f3ac{padding:0 0 0 20px!important;background:transparent!important;border:none!important;font-size:14px!important;color:#9ca3af!important;font-weight:400!important;line-height:20px!important;min-height:20px!important}.openai-mcp-tools.jsx-32b14b04f420f3ac .ant-collapse-header.jsx-32b14b04f420f3ac:hover{background:transparent!important;color:#6b7280!important}.openai-mcp-tools.jsx-32b14b04f420f3ac .ant-collapse-content.jsx-32b14b04f420f3ac{border:none!important;background:transparent!important}.openai-mcp-tools.jsx-32b14b04f420f3ac .ant-collapse-content-box.jsx-32b14b04f420f3ac{padding:4px 0 0 20px!important}.openai-mcp-tools.jsx-32b14b04f420f3ac .ant-collapse-expand-icon.jsx-32b14b04f420f3ac{position:absolute!important;left:2px!important;top:2px!important;color:#9ca3af!important;font-size:10px!important;width:16px!important;height:16px!important;display:-webkit-box!important;display:-webkit-flex!important;display:-moz-box!important;display:-ms-flexbox!important;display:flex!important;-webkit-box-align:center!important;-webkit-align-items:center!important;-moz-box-align:center!important;-ms-flex-align:center!important;align-items:center!important;-webkit-box-pack:center!important;-webkit-justify-content:center!important;-moz-box-pack:center!important;-ms-flex-pack:center!important;justify-content:center!important}.openai-mcp-tools.jsx-32b14b04f420f3ac .ant-collapse-expand-icon.jsx-32b14b04f420f3ac:hover{color:#6b7280!important}.openai-vertical-line.jsx-32b14b04f420f3ac{position:absolute;left:9px;top:18px;bottom:0;width:.5px;background-color:#f3f4f6;opacity:.8}.tool-item.jsx-32b14b04f420f3ac{font-family:ui-monospace,SFMono-Regular,"SF Mono",Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:13px;color:#4b5563;line-height:18px;padding:0;margin:0;background:white;position:relative;z-index:1}.mcp-section.jsx-32b14b04f420f3ac{margin-bottom:12px;background:white;position:relative;z-index:1}.mcp-section.jsx-32b14b04f420f3ac:last-child{margin-bottom:0}.mcp-section-header.jsx-32b14b04f420f3ac{font-size:13px;color:#6b7280;font-weight:500;margin-bottom:4px}.mcp-code-block.jsx-32b14b04f420f3ac{background:#f9fafb;border:1px solid#f3f4f6;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;padding:8px;font-size:12px}.mcp-json.jsx-32b14b04f420f3ac{font-family:ui-monospace,SFMono-Regular,"SF Mono",Monaco,Consolas,"Liberation Mono","Courier New",monospace;color:#374151;margin:0;white-space:pre-wrap;word-wrap:break-word}.mcp-approved.jsx-32b14b04f420f3ac{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;-ms-flex-align:center;align-items:center;font-size:13px;color:#6b7280}.mcp-checkmark.jsx-32b14b04f420f3ac{color:#10b981;margin-right:6px;font-weight:bold}.mcp-response-content.jsx-32b14b04f420f3ac{font-size:13px;color:#374151;line-height:1.5;white-space:pre-wrap;font-family:ui-monospace,SFMono-Regular,"SF Mono",Monaco,Consolas,"Liberation Mono","Courier New",monospace}'}),(0,a.jsxs)("div",{className:"jsx-32b14b04f420f3ac openai-mcp-tools",children:[(0,a.jsx)("div",{className:"jsx-32b14b04f420f3ac openai-vertical-line"}),(0,a.jsxs)(eO.default,{ghost:!0,size:"small",expandIconPosition:"start",defaultActiveKey:o?["list-tools"]:n.map((e,t)=>"mcp-call-".concat(t)),children:[o&&(0,a.jsx)(eV,{header:"List tools",children:(0,a.jsx)("div",{className:"jsx-32b14b04f420f3ac",children:null===(s=o.item)||void 0===s?void 0:null===(t=s.tools)||void 0===t?void 0:t.map((e,t)=>(0,a.jsx)("div",{className:"jsx-32b14b04f420f3ac tool-item",children:e.name},t))})},"list-tools"),n.map((e,t)=>{var s,r,l;return(0,a.jsx)(eV,{header:(null===(s=e.item)||void 0===s?void 0:s.name)||"Tool call",children:(0,a.jsxs)("div",{className:"jsx-32b14b04f420f3ac",children:[(0,a.jsxs)("div",{className:"jsx-32b14b04f420f3ac mcp-section",children:[(0,a.jsx)("div",{className:"jsx-32b14b04f420f3ac mcp-section-header",children:"Request"}),(0,a.jsx)("div",{className:"jsx-32b14b04f420f3ac mcp-code-block",children:(null===(r=e.item)||void 0===r?void 0:r.arguments)&&(0,a.jsx)("pre",{className:"jsx-32b14b04f420f3ac mcp-json",children:(()=>{try{return JSON.stringify(JSON.parse(e.item.arguments),null,2)}catch(t){return e.item.arguments}})()})})]}),(0,a.jsx)("div",{className:"jsx-32b14b04f420f3ac mcp-section",children:(0,a.jsxs)("div",{className:"jsx-32b14b04f420f3ac mcp-approved",children:[(0,a.jsx)("span",{className:"jsx-32b14b04f420f3ac mcp-checkmark",children:"✓"})," Approved"]})}),(null===(l=e.item)||void 0===l?void 0:l.output)&&(0,a.jsxs)("div",{className:"jsx-32b14b04f420f3ac mcp-section",children:[(0,a.jsx)("div",{className:"jsx-32b14b04f420f3ac mcp-section-header",children:"Response"}),(0,a.jsx)("div",{className:"jsx-32b14b04f420f3ac mcp-response-content",children:e.item.output})]})]})},"mcp-call-".concat(t))})]})]})]}):(console.log("MCPEventsDisplay: No valid events found, returning null"),null)},eX=s(94331),e$=s(38398);let eQ=e=>new Promise((t,s)=>{let a=new FileReader;a.onload=()=>{t(a.result.split(",")[1])},a.onerror=s,a.readAsDataURL(e)}),e0=async(e,t)=>{let s=await eQ(t),a=t.type||(t.name.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg");return{role:"user",content:[{type:"input_text",text:e},{type:"input_image",image_url:"data:".concat(a,";base64,").concat(s)}]}},e1=(e,t,s,a)=>{let r="";t&&a&&(r=a.toLowerCase().endsWith(".pdf")?"[PDF attached]":"[Image attached]");let l={role:"user",content:t?"".concat(e," ").concat(r):e};return t&&s&&(l.imagePreviewUrl=s),l},e2=e=>"user"===e.role&&"string"==typeof e.content&&(e.content.includes("[Image attached]")||e.content.includes("[PDF attached]"))&&!!e.imagePreviewUrl;var e4=e=>{let{message:t}=e;if(!e2(t))return null;let s="string"==typeof t.content&&t.content.includes("[PDF attached]");return(0,a.jsx)("div",{className:"mb-2",children:s?(0,a.jsx)("div",{className:"w-64 h-32 rounded-md border border-gray-200 bg-red-50 flex items-center justify-center",children:(0,a.jsx)(j.Z,{style:{fontSize:"48px",color:"#dc2626"}})}):(0,a.jsx)("img",{src:t.imagePreviewUrl,alt:"User uploaded image",className:"max-w-64 rounded-md border border-gray-200 shadow-sm",style:{maxHeight:"200px"}})})},e3=s(53508);let{Dragger:e5}=_.default;var e6=e=>{let{responsesUploadedImage:t,responsesImagePreviewUrl:s,onImageUpload:r,onRemoveImage:l}=e;return(0,a.jsx)(a.Fragment,{children:!t&&(0,a.jsx)(e5,{beforeUpload:r,accept:"image/*,.pdf",showUploadList:!1,className:"inline-block",style:{padding:0,border:"none",background:"none"},children:(0,a.jsx)(E.Z,{title:"Attach image or PDF",children:(0,a.jsx)("button",{type:"button",className:"flex items-center justify-center w-8 h-8 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-md transition-colors",children:(0,a.jsx)(e3.Z,{style:{fontSize:"16px"}})})})})})},e7=s(33152),e8=e=>{let{endpointType:t,responsesSessionId:s,useApiSessionManagement:r,onToggleSessionManagement:l}=e;return t!==eA.KP.RESPONSES?null:(0,a.jsxs)("div",{className:"mb-4",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Session Management"}),(0,a.jsx)(E.Z,{title:"Choose between LiteLLM API session management (using previous_response_id) or UI-based session management (using chat history)",children:(0,a.jsx)(x.Z,{className:"text-gray-400",style:{fontSize:"12px"}})})]}),(0,a.jsx)(eB.Z,{checked:r,onChange:l,checkedChildren:"API",unCheckedChildren:"UI",size:"small"})]}),(0,a.jsxs)("div",{className:"text-xs p-2 rounded-md ".concat(s?"bg-green-50 text-green-700 border border-green-200":"bg-blue-50 text-blue-700 border border-blue-200"),children:[(0,a.jsxs)("div",{className:"flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)(x.Z,{style:{fontSize:"12px"}}),(()=>{if(!s)return r?"API Session: Ready":"UI Session: Ready";let e=r?"Response ID":"UI Session",t=s.slice(0,10);return"".concat(e,": ").concat(t,"...")})()]}),s&&(0,a.jsx)(E.Z,{title:(0,a.jsxs)("div",{className:"text-xs",children:[(0,a.jsx)("div",{className:"mb-1",children:"Copy response ID to continue session:"}),(0,a.jsx)("div",{className:"bg-gray-800 text-gray-100 p-2 rounded font-mono text-xs whitespace-pre-wrap",children:'curl -X POST "your-proxy-url/v1/responses" \\\n -H "Authorization: Bearer your-api-key" \\\n -H "Content-Type: application/json" \\\n -d \'{\n "model": "your-model",\n "input": [{"role": "user", "content": "your message", "type": "message"}],\n "previous_response_id": "'.concat(s,'",\n "stream": true\n }\'')})]}),overlayStyle:{maxWidth:"500px"},children:(0,a.jsx)("button",{onClick:()=>{s&&(navigator.clipboard.writeText(s),W.ZP.success("Response ID copied to clipboard!"))},className:"ml-2 p-1 hover:bg-green-100 rounded transition-colors",children:(0,a.jsx)(eg.Z,{style:{fontSize:"12px"}})})})]}),(0,a.jsx)("div",{className:"text-xs opacity-75 mt-1",children:s?r?"LiteLLM API session active - context maintained server-side":"UI session active - context maintained client-side":r?"LiteLLM will manage session using previous_response_id":"UI will manage session using chat history"})]})]})};let{TextArea:e9}=S.default,{Dragger:te}=_.default,tt=new Set([eA.KP.CHAT,eA.KP.RESPONSES,eA.KP.MCP]);var ts=e=>{let{accessToken:t,token:s,userRole:S,userID:_,disabledPersonalKeyCreation:B,proxySettings:z}=e,[F,H]=(0,T.useState)([]),[G,q]=(0,T.useState)(()=>{let e=sessionStorage.getItem("selectedMCPServers");try{return e?JSON.parse(e):[]}catch(e){return console.error("Error parsing selectedMCPServers from sessionStorage",e),[]}}),[Q,et]=(0,T.useState)(!1),[em,eu]=(0,T.useState)({}),[ep,ex]=(0,T.useState)(void 0),eg=(0,T.useRef)(null),[eh,ef]=(0,T.useState)(()=>{let e=sessionStorage.getItem("mcpServerToolRestrictions");try{return e?JSON.parse(e):{}}catch(e){return console.error("Error parsing mcpServerToolRestrictions from sessionStorage",e),{}}}),[ev,ey]=(0,T.useState)(()=>{let e=sessionStorage.getItem("apiKeySource");if(e)try{return JSON.parse(e)}catch(e){console.error("Error parsing apiKeySource from sessionStorage",e)}return B?"custom":"session"}),[eb,ej]=(0,T.useState)(()=>sessionStorage.getItem("apiKey")||""),[eN,eS]=(0,T.useState)(()=>sessionStorage.getItem("customProxyBaseUrl")||""),[e_,eP]=(0,T.useState)(""),[eE,eZ]=(0,T.useState)(()=>{try{let e=sessionStorage.getItem("chatHistory");return e?JSON.parse(e):[]}catch(e){return console.error("Error parsing chatHistory from sessionStorage",e),[]}}),[eO,eR]=(0,T.useState)(void 0),[eK,eD]=(0,T.useState)(!1),[eB,ez]=(0,T.useState)([]),[eq,eJ]=(0,T.useState)([]),[eW,eV]=(0,T.useState)(void 0),eQ=(0,T.useRef)(null),[e2,e3]=(0,T.useState)(()=>sessionStorage.getItem("endpointType")||eA.KP.CHAT),[e5,ts]=(0,T.useState)(!1),ta=(0,T.useRef)(null),[tr,tl]=(0,T.useState)(()=>{let e=sessionStorage.getItem("selectedTags");try{return e?JSON.parse(e):[]}catch(e){return console.error("Error parsing selectedTags from sessionStorage",e),[]}}),[to,tn]=(0,T.useState)(()=>{let e=sessionStorage.getItem("selectedVoice");if(!e)return"alloy";try{return JSON.parse(e)}catch(t){return e}}),[ti,tc]=(0,T.useState)(()=>{let e=sessionStorage.getItem("selectedVectorStores");try{return e?JSON.parse(e):[]}catch(e){return console.error("Error parsing selectedVectorStores from sessionStorage",e),[]}}),[td,tm]=(0,T.useState)(()=>{let e=sessionStorage.getItem("selectedGuardrails");try{return e?JSON.parse(e):[]}catch(e){return console.error("Error parsing selectedGuardrails from sessionStorage",e),[]}}),[tu,tp]=(0,T.useState)(()=>{let e=sessionStorage.getItem("selectedPolicies");try{return e?JSON.parse(e):[]}catch(e){return console.error("Error parsing selectedPolicies from sessionStorage",e),[]}}),[tx,tg]=(0,T.useState)(()=>sessionStorage.getItem("messageTraceId")||null),[th,tf]=(0,T.useState)(()=>sessionStorage.getItem("responsesSessionId")||null),[tv,ty]=(0,T.useState)(()=>{let e=sessionStorage.getItem("useApiSessionManagement");return!e||JSON.parse(e)}),[tb,tj]=(0,T.useState)([]),[tN,tw]=(0,T.useState)([]),[tS,t_]=(0,T.useState)(null),[tP,tC]=(0,T.useState)(null),[tk,tA]=(0,T.useState)(null),[tE,tI]=(0,T.useState)(null),[tZ,tT]=(0,T.useState)(null),[tL,tM]=(0,T.useState)(!1),[tO,tR]=(0,T.useState)(""),[tK,tU]=(0,T.useState)("openai"),[tD,tB]=(0,T.useState)([]),[tz,tF]=(0,T.useState)(1),[tH,tG]=(0,T.useState)(2048),[tq,tJ]=(0,T.useState)(!1),tW=function(){let[e,t]=(0,T.useState)(()=>{let e=sessionStorage.getItem("codeInterpreterEnabled");return!!e&&JSON.parse(e)}),[s,a]=(0,T.useState)(null),r=(0,T.useCallback)(e=>{t(e),sessionStorage.setItem("codeInterpreterEnabled",JSON.stringify(e))},[]),l=(0,T.useCallback)(()=>{a(null)},[]),o=(0,T.useCallback)(()=>{r(!e)},[e,r]);return{enabled:e,result:s,setEnabled:r,setResult:a,clearResult:l,toggle:o}}(),tV=(0,T.useRef)(null),tY=async()=>{let e="session"===ev?t:eb;if(e){et(!0);try{let t=await (0,V.fetchMCPServers)(e);H(Array.isArray(t)?t:t.data||[])}catch(e){console.error("Error fetching MCP servers:",e)}finally{et(!1)}}},tX=async e=>{let s="session"===ev?t:eb;if(s&&!em[e])try{let t=await (0,V.listMCPTools)(s,e);eu(s=>({...s,[e]:t.tools||[]}))}catch(t){console.error("Error fetching tools for server ".concat(e,":"),t)}};(0,T.useEffect)(()=>{tL&&tR((0,eH.L)({apiKeySource:ev,accessToken:t,apiKey:eb,inputMessage:e_,chatHistory:eE,selectedTags:tr,selectedVectorStores:ti,selectedGuardrails:td,selectedPolicies:tu,selectedMCPServers:G,mcpServers:F,mcpServerToolRestrictions:eh,endpointType:e2,selectedModel:eO,selectedSdk:tK,selectedVoice:to,proxySettings:z}))},[tL,tK,ev,t,eb,e_,eE,tr,ti,td,tu,G,F,eh,e2,eO,z]),(0,T.useEffect)(()=>{let e=setTimeout(()=>{sessionStorage.setItem("chatHistory",JSON.stringify(eE))},500);return()=>{clearTimeout(e)}},[eE]),(0,T.useEffect)(()=>{sessionStorage.setItem("apiKeySource",JSON.stringify(ev)),sessionStorage.setItem("apiKey",eb),sessionStorage.setItem("endpointType",e2),sessionStorage.setItem("selectedTags",JSON.stringify(tr)),sessionStorage.setItem("selectedVectorStores",JSON.stringify(ti)),sessionStorage.setItem("selectedGuardrails",JSON.stringify(td)),sessionStorage.setItem("selectedPolicies",JSON.stringify(tu)),sessionStorage.setItem("selectedMCPServers",JSON.stringify(G)),sessionStorage.setItem("mcpServerToolRestrictions",JSON.stringify(eh)),sessionStorage.setItem("selectedVoice",to),sessionStorage.removeItem("selectedMCPTools"),eO?sessionStorage.setItem("selectedModel",eO):sessionStorage.removeItem("selectedModel"),tx?sessionStorage.setItem("messageTraceId",tx):sessionStorage.removeItem("messageTraceId"),th?sessionStorage.setItem("responsesSessionId",th):sessionStorage.removeItem("responsesSessionId"),sessionStorage.setItem("useApiSessionManagement",JSON.stringify(tv))},[ev,eb,eO,e2,tr,ti,td,tu,tx,th,tv,G,eh,to]),(0,T.useEffect)(()=>{let e="session"===ev?t:eb;if(!e||!s||!S||!_){console.log("userApiKey or token or userRole or userID is missing = ",e,s,S,_);return}(async()=>{try{if(!e){console.log("userApiKey is missing");return}let t=await (0,en.p)(e);console.log("Fetched models:",t),ez(t);let s=t.some(e=>e.model_group===eO);t.length&&s||eR(void 0)}catch(e){console.error("Error fetching model info:",e)}})(),tY()},[t,_,S,ev,eb,s]),(0,T.useEffect)(()=>{e2!==eA.KP.MCP||1!==G.length||"__all__"===G[0]||em[G[0]]||tX(G[0])},[e2,G,em]),(0,T.useEffect)(()=>{let e="session"===ev?t:eb;e&&e2===eA.KP.A2A_AGENTS&&(async()=>{try{let t=await (0,eo.o)(e,eN||void 0);eJ(t),eW&&!t.some(e=>e.agent_name===eW)&&eV(void 0)}catch(e){console.error("Error fetching agents:",e)}})()},[t,ev,eb,e2,eN,eW]),(0,T.useEffect)(()=>{tV.current&&setTimeout(()=>{var e;null===(e=tV.current)||void 0===e||e.scrollIntoView({behavior:"smooth",block:"end"})},100)},[eE]);let t$=(e,t,s)=>{console.log("updateTextUI called with:",e,t,s),eZ(a=>{let r=a[a.length-1];if(!r||r.role!==e||r.isImage||r.isAudio)return[...a,{role:e,content:t,model:s}];{var l;let e={...r,content:r.content+t,model:null!==(l=r.model)&&void 0!==l?l:s};return[...a.slice(0,-1),e]}})},tQ=e=>{eZ(t=>{let s=t[t.length-1];return!s||"assistant"!==s.role||s.isImage||s.isAudio?t.length>0&&"user"===t[t.length-1].role?[...t,{role:"assistant",content:"",reasoningContent:e}]:t:[...t.slice(0,t.length-1),{...s,reasoningContent:(s.reasoningContent||"")+e}]})},t0=e=>{console.log("updateTimingData called with:",e),eZ(t=>{let s=t[t.length-1];if(console.log("Current last message:",s),s&&"assistant"===s.role){console.log("Updating assistant message with timeToFirstToken:",e);let a=[...t.slice(0,t.length-1),{...s,timeToFirstToken:e}];return console.log("Updated chat history:",a),a}return s&&"user"===s.role?(console.log("Creating new assistant message with timeToFirstToken:",e),[...t,{role:"assistant",content:"",timeToFirstToken:e}]):(console.log("No appropriate message found to update timing"),t)})},t1=(e,t)=>{console.log("Received usage data:",e),eZ(s=>{let a=s[s.length-1];if(a&&"assistant"===a.role){console.log("Updating message with usage data:",e);let r={...a,usage:e,toolName:t};return console.log("Updated message:",r),[...s.slice(0,s.length-1),r]}return s})},t2=e=>{console.log("Received A2A metadata:",e),eZ(t=>{let s=t[t.length-1];if(s&&"assistant"===s.role){let a={...s,a2aMetadata:e};return[...t.slice(0,t.length-1),a]}return t})},t4=e=>{eZ(t=>{let s=t[t.length-1];return s&&"assistant"===s.role?[...t.slice(0,t.length-1),{...s,totalLatency:e}]:t})},t3=e=>{console.log("Received search results:",e),eZ(t=>{let s=t[t.length-1];if(s&&"assistant"===s.role){console.log("Updating message with search results");let a={...s,searchResults:e};return[...t.slice(0,t.length-1),a]}return t})},t5=e=>{console.log("Received response ID for session management:",e),tv&&tf(e)},t6=e=>{console.log("ChatUI: Received MCP event:",e),tB(t=>{if(e.item_id&&t.some(t=>t.item_id===e.item_id&&t.type===e.type&&(t.sequence_number===e.sequence_number||void 0===t.sequence_number&&void 0===e.sequence_number)))return console.log("ChatUI: Duplicate MCP event, skipping"),t;let s=[...t,e];return console.log("ChatUI: Updated MCP events:",s),s})},t7=(e,t)=>{eZ(s=>[...s,{role:"assistant",content:e,model:t,isImage:!0}])},t8=(e,t)=>{eZ(s=>[...s,{role:"assistant",content:(0,K.aS)(e,100),model:t,isEmbeddings:!0}])},t9=(e,t)=>{eZ(s=>[...s,{role:"assistant",content:e,model:t,isAudio:!0}])},se=(e,t)=>{eZ(s=>{let a=s[s.length-1];if(!a||"assistant"!==a.role||a.isImage||a.isAudio)return[...s,{role:"assistant",content:"",model:t,image:{url:e,detail:"auto"}}];{var r;let l={...a,image:{url:e,detail:"auto"},model:null!==(r=a.model)&&void 0!==r?r:t};return[...s.slice(0,-1),l]}})},st=e=>{tj(t=>[...t,e]);let t=URL.createObjectURL(e);return tw(e=>[...e,t]),!1},ss=e=>{tN[e]&&URL.revokeObjectURL(tN[e]),tj(t=>t.filter((t,s)=>s!==e)),tw(t=>t.filter((t,s)=>s!==e))},sa=()=>{tN.forEach(e=>{URL.revokeObjectURL(e)}),tj([]),tw([])},sr=()=>{tP&&URL.revokeObjectURL(tP),t_(null),tC(null)},sl=()=>{tE&&URL.revokeObjectURL(tE),tA(null),tI(null)},so=()=>{tT(null)},sn=async()=>{var e,a,r;let l;if(""===e_.trim()&&e2!==eA.KP.TRANSCRIPTION&&e2!==eA.KP.MCP)return;if(e2===eA.KP.IMAGE_EDITS&&0===tb.length){W.ZP.fromBackend("Please upload at least one image for editing");return}if(e2===eA.KP.TRANSCRIPTION&&!tZ){W.ZP.fromBackend("Please upload an audio file for transcription");return}if(e2===eA.KP.A2A_AGENTS&&!eW){W.ZP.fromBackend("Please select an agent to send a message");return}let o={};if(e2===eA.KP.MCP){if(!(1===G.length&&"__all__"!==G[0]?G[0]:null)){W.ZP.fromBackend("Please select an MCP server to test");return}if(!ep){W.ZP.fromBackend("Please select an MCP tool to call");return}if(!(em[G[0]]||[]).find(e=>e.name===ep)){W.ZP.fromBackend("Please wait for tool schema to load");return}try{o=null!==(a=await (null===(e=eg.current)||void 0===e?void 0:e.getSubmitValues()))&&void 0!==a?a:{}}catch(e){W.ZP.fromBackend(e instanceof Error?e.message:"Please fill in all required parameters");return}}if([eA.KP.CHAT,eA.KP.IMAGE,eA.KP.SPEECH,eA.KP.IMAGE_EDITS,eA.KP.RESPONSES,eA.KP.ANTHROPIC_MESSAGES,eA.KP.EMBEDDINGS,eA.KP.TRANSCRIPTION].includes(e2)&&!eO){W.ZP.fromBackend("Please select a model before sending a request");return}if(!s||!S||!_)return;let n="session"===ev?t:eb;if(!n){W.ZP.fromBackend("Please provide a Virtual Key or select Current UI Session");return}ta.current=new AbortController;let i=ta.current.signal;if(e2===eA.KP.RESPONSES&&tS)try{l=await e0(e_,tS)}catch(e){W.ZP.fromBackend("Failed to process image. Please try again.");return}else if(e2===eA.KP.CHAT&&tk)try{l=await (0,eM.Sn)(e_,tk)}catch(e){W.ZP.fromBackend("Failed to process image. Please try again.");return}else l={role:"user",content:e_};let c=tx||(0,R.Z)();tx||tg(c),eZ([...eE,e2===eA.KP.RESPONSES&&tS?e1(e_,!0,tP||void 0,tS.name):e2===eA.KP.CHAT&&tk?(0,eM.Hk)(e_,!0,tE||void 0,tk.name):e2===eA.KP.TRANSCRIPTION&&tZ?e1(e_?"\uD83C\uDFB5 Audio file: ".concat(tZ.name,"\nPrompt: ").concat(e_):"\uD83C\uDFB5 Audio file: ".concat(tZ.name),!1):e2===eA.KP.MCP&&ep?e1("\uD83D\uDD27 MCP Tool: ".concat(ep,"\nArguments: ").concat(JSON.stringify(o,null,2)),!1):e1(e_,!1)]),tB([]),tW.clearResult(),ts(!0);try{if(eO){if(e2===eA.KP.CHAT){let e=[...eE.filter(e=>!e.isImage&&!e.isAudio).map(e=>{let{role:t,content:s}=e;return{role:t,content:"string"==typeof s?s:""}}),l];await (0,er.n)(e,(e,t)=>t$("assistant",e,t),eO,n,tr,i,tQ,t0,t1,c,ti.length>0?ti:void 0,td.length>0?td:void 0,tu.length>0?tu:void 0,G,se,t3,tq?tz:void 0,tq?tH:void 0,t4,eN||void 0,F,eh,t6)}else if(e2===eA.KP.IMAGE)await ec(e_,(e,t)=>t7(e,t),eO,n,tr,i,eN||void 0);else if(e2===eA.KP.SPEECH)await es(e_,to,(e,t)=>t9(e,t),eO||"",n,tr,i,void 0,void 0,eN||void 0);else if(e2===eA.KP.IMAGE_EDITS)tb.length>0&&await ei(1===tb.length?tb[0]:tb,e_,(e,t)=>t7(e,t),eO,n,tr,i,eN||void 0);else if(e2===eA.KP.RESPONSES){let e;e=tv&&th?[l]:[...eE.filter(e=>!e.isImage&&!e.isAudio).map(e=>{let{role:t,content:s}=e;return{role:t,content:s}}),l],await ed(e,(e,t,s)=>t$(e,t,s),eO,n,tr,i,tQ,t0,t1,c,ti.length>0?ti:void 0,td.length>0?td:void 0,tu.length>0?tu:void 0,G,tv?th:null,t5,t6,tW.enabled,tW.setResult,eN||void 0,F,eh)}else if(e2===eA.KP.ANTHROPIC_MESSAGES){let e=[...eE.filter(e=>!e.isImage&&!e.isAudio).map(e=>{let{role:t,content:s}=e;return{role:t,content:s}}),l];await ee(e,(e,t,s)=>t$(e,t,s),eO,n,tr,i,tQ,t0,t1,c,ti.length>0?ti:void 0,td.length>0?td:void 0,tu.length>0?tu:void 0,G,eN||void 0)}else e2===eA.KP.EMBEDDINGS?await el(e_,(e,t)=>t8(e,t),eO,n,tr,eN||void 0):e2===eA.KP.TRANSCRIPTION&&tZ&&await ea(tZ,(e,t)=>t$("assistant",e,t),eO,n,tr,i,void 0,void 0,void 0,void 0,eN||void 0)}if(e2===eA.KP.MCP){let e=1===G.length&&"__all__"!==G[0]?G[0]:null;if(e&&ep){let t=await (0,V.callMCPTool)(n,e,ep,o,td.length>0?{guardrails:td}:void 0),s=(null==t?void 0:null===(r=t.content)||void 0===r?void 0:r.length)>0?JSON.stringify(t.content.map(e=>"text"===e.type?e.text:e).filter(Boolean),null,2):JSON.stringify(t,null,2);t$("assistant",s||"Tool executed successfully.")}}e2===eA.KP.A2A_AGENTS&&eW&&await (0,$.O)(eW,e_,(e,t)=>t$("assistant",e,t),n,i,t0,t4,t2,eN||void 0,td.length>0?td:void 0)}catch(e){i.aborted?console.log("Request was cancelled"):(console.error("Error fetching response",e),t$("assistant","Error fetching response:"+e))}finally{ts(!1),ta.current=null,e2===eA.KP.IMAGE_EDITS&&sa(),e2===eA.KP.RESPONSES&&tS&&sr(),e2===eA.KP.CHAT&&tk&&sl(),e2===eA.KP.TRANSCRIPTION&&tZ&&so()}eP("")};if(S&&"Admin Viewer"===S){let{Title:e,Paragraph:t}=P.default;return(0,a.jsxs)("div",{children:[(0,a.jsx)(e,{level:1,children:"Access Denied"}),(0,a.jsx)(t,{children:"Ask your proxy admin for access to test models"})]})}let si=(0,a.jsx)(r.Z,{style:{fontSize:24},spin:!0});return(0,a.jsxs)("div",{className:"w-full p-4 pb-0 bg-white",children:[(0,a.jsx)(w.Zb,{className:"w-full rounded-xl shadow-md overflow-hidden",children:(0,a.jsxs)("div",{className:"flex h-[80vh] w-full gap-4",children:[(0,a.jsxs)("div",{className:"w-1/4 p-4 bg-gray-50 overflow-y-auto",children:[(0,a.jsx)(w.Dx,{className:"text-xl font-semibold mb-6 mt-2",children:"Configurations"}),(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(l.Z,{className:"mr-2"})," Virtual Key Source"]}),(0,a.jsx)(C.default,{disabled:B,value:ev,style:{width:"100%"},onChange:e=>{ey(e)},options:[{value:"session",label:"Current UI Session"},{value:"custom",label:"Virtual Key"}],className:"rounded-md"}),"custom"===ev&&(0,a.jsx)(w.oi,{className:"mt-2",placeholder:"Enter custom Virtual Key",type:"password",onValueChange:ej,value:eb,icon:l.Z})]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,a.jsxs)(w.xv,{className:"font-medium block text-gray-700 flex items-center",children:[(0,a.jsx)(o.Z,{className:"mr-2"})," Custom Proxy Base URL"]}),(null==z?void 0:z.LITELLM_UI_API_DOC_BASE_URL)&&!eN&&(0,a.jsx)(k.ZP,{type:"link",size:"small",icon:(0,a.jsx)(n.Z,{}),onClick:()=>{eS(z.LITELLM_UI_API_DOC_BASE_URL||""),sessionStorage.setItem("customProxyBaseUrl",z.LITELLM_UI_API_DOC_BASE_URL||"")},className:"text-gray-500 hover:text-gray-700",children:"Fill"}),eN&&(0,a.jsx)(k.ZP,{type:"link",size:"small",icon:(0,a.jsx)(i.Z,{}),onClick:()=>{eS(""),sessionStorage.removeItem("customProxyBaseUrl")},className:"text-gray-500 hover:text-gray-700",children:"Clear"})]}),(0,a.jsx)(w.oi,{placeholder:"Optional: Enter custom proxy URL (e.g., http://localhost:5000)",onValueChange:e=>{eS(e),sessionStorage.setItem("customProxyBaseUrl",e)},value:eN,icon:c.Z}),eN&&(0,a.jsxs)(w.xv,{className:"text-xs text-gray-500 mt-1",children:["API calls will be sent to: ",eN]})]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(c.Z,{className:"mr-2"})," Endpoint Type"]}),(0,a.jsx)(eG,{endpointType:e2,onEndpointChange:e=>{e3(e),eR(void 0),eV(void 0),eD(!1),ex(void 0),e===eA.KP.MCP&&q(e=>1===e.length&&"__all__"!==e[0]?e:[]);try{sessionStorage.removeItem("selectedModel"),sessionStorage.removeItem("selectedAgent")}catch(e){}},className:"mb-4"}),e2===eA.KP.SPEECH&&(0,a.jsxs)("div",{className:"mb-4",children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(d.Z,{className:"mr-2"}),"Voice"]}),(0,a.jsx)(C.default,{value:to,onChange:e=>{tn(e),sessionStorage.setItem("selectedVoice",e)},style:{width:"100%"},className:"rounded-md",options:eI})]}),(0,a.jsx)(e8,{endpointType:e2,responsesSessionId:th,useApiSessionManagement:tv,onToggleSessionManagement:e=>{ty(e),e||tf(null)}})]}),e2!==eA.KP.A2A_AGENTS&&e2!==eA.KP.MCP&&(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center justify-between",children:[(0,a.jsxs)("span",{className:"flex items-center",children:[(0,a.jsx)(m.Z,{className:"mr-2"})," Select Model"]}),(()=>{if(!eO||"custom"===eO)return!1;let e=eB.find(e=>e.model_group===eO);return!!e&&(!e.mode||"chat"===e.mode)})()?(0,a.jsx)(A.Z,{content:(0,a.jsx)(eC,{temperature:tz,maxTokens:tH,useAdvancedParams:tq,onTemperatureChange:tF,onMaxTokensChange:tG,onUseAdvancedParamsChange:tJ}),title:"Model Settings",trigger:"click",placement:"right",children:(0,a.jsx)(k.ZP,{type:"text",size:"small",icon:(0,a.jsx)(o.Z,{}),className:"text-gray-500 hover:text-gray-700"})}):(0,a.jsx)(E.Z,{title:"Advanced parameters are only supported for chat models currently",children:(0,a.jsx)(k.ZP,{type:"text",size:"small",icon:(0,a.jsx)(o.Z,{}),className:"text-gray-300 cursor-not-allowed",disabled:!0})})]}),(0,a.jsx)(C.default,{value:eO,placeholder:"Select a Model",onChange:e=>{console.log("selected ".concat(e)),eR(e),eD("custom"===e)},options:[{value:"custom",label:"Enter custom model",key:"custom"},...Array.from(new Set(eB.filter(e=>{if(!e.mode)return!0;let t=(0,eA.vf)(e.mode);return e2===eA.KP.RESPONSES||e2===eA.KP.ANTHROPIC_MESSAGES?t===e2||t===eA.KP.CHAT:e2===eA.KP.IMAGE_EDITS?t===e2||t===eA.KP.IMAGE:t===e2}).map(e=>e.model_group))).map((e,t)=>({value:e,label:e,key:t}))],style:{width:"100%"},showSearch:!0,className:"rounded-md"}),eK&&(0,a.jsx)(w.oi,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{eQ.current&&clearTimeout(eQ.current),eQ.current=setTimeout(()=>{eR(e)},500)}})]}),e2===eA.KP.A2A_AGENTS&&(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(m.Z,{className:"mr-2"})," Select Agent"]}),(0,a.jsx)(C.default,{value:eW,placeholder:"Select an Agent",onChange:e=>eV(e),options:eq.map(e=>({value:e.agent_name,label:e.agent_name||e.agent_id,key:e.agent_id})),style:{width:"100%"},showSearch:!0,className:"rounded-md",optionLabelProp:"label",children:eq.map(e=>{var t;return(0,a.jsx)(C.default.Option,{value:e.agent_name,label:e.agent_name||e.agent_id,children:(0,a.jsxs)("div",{className:"flex flex-col py-1",children:[(0,a.jsx)("span",{className:"font-medium",children:e.agent_name||e.agent_id}),(null===(t=e.agent_card_params)||void 0===t?void 0:t.description)&&(0,a.jsx)("span",{className:"text-xs text-gray-500 mt-1",children:e.agent_card_params.description})]})},e.agent_id)})}),0===eq.length&&(0,a.jsx)(w.xv,{className:"text-xs text-gray-500 mt-2 block",children:"No agents found. Create agents via /v1/agents endpoint."})]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(u.Z,{className:"mr-2"})," Tags"]}),(0,a.jsx)(Y.Z,{value:tr,onChange:tl,className:"mb-4",accessToken:t||""})]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(p.Z,{className:"mr-2"}),e2===eA.KP.MCP?"MCP Server":"MCP Servers",(0,a.jsx)(E.Z,{className:"ml-1",title:e2===eA.KP.MCP?"Select an MCP server to test tools directly.":"Select MCP servers to use in your conversation.",children:(0,a.jsx)(x.Z,{})})]}),(0,a.jsxs)(C.default,{mode:e2===eA.KP.MCP?void 0:"multiple",style:{width:"100%"},placeholder:e2===eA.KP.MCP?"Select MCP server":"Select MCP servers",value:e2===eA.KP.MCP?"__all__"!==G[0]&&1===G.length?G[0]:void 0:G,onChange:e=>{e2===eA.KP.MCP?(q(e?[e]:[]),ex(void 0),e&&!em[e]&&tX(e)):e.includes("__all__")?(q(["__all__"]),ef({})):(q(e),ef(t=>{let s={...t};return Object.keys(s).forEach(t=>{e.includes(t)||delete s[t]}),s}),e.forEach(e=>{em[e]||tX(e)}))},loading:Q,className:"mb-2",allowClear:!0,optionLabelProp:"label",disabled:!tt.has(e2),maxTagCount:e2===eA.KP.MCP?1:"responsive",children:[e2!==eA.KP.MCP&&(0,a.jsx)(C.default.Option,{value:"__all__",label:"All MCP Servers",children:(0,a.jsxs)("div",{className:"flex flex-col py-1",children:[(0,a.jsx)("span",{className:"font-medium",children:"All MCP Servers"}),(0,a.jsx)("span",{className:"text-xs text-gray-500 mt-1",children:"Use all available MCP servers"})]})},"__all__"),F.map(e=>(0,a.jsx)(C.default.Option,{value:e.server_id,label:e.alias||e.server_name||e.server_id,disabled:e2!==eA.KP.MCP&&G.includes("__all__"),children:(0,a.jsxs)("div",{className:"flex flex-col py-1",children:[(0,a.jsx)("span",{className:"font-medium",children:e.alias||e.server_name||e.server_id}),e.description&&(0,a.jsx)("span",{className:"text-xs text-gray-500 mt-1",children:e.description})]})},e.server_id))]}),e2===eA.KP.MCP&&1===G.length&&"__all__"!==G[0]&&(0,a.jsxs)("div",{className:"mt-3",children:[(0,a.jsx)(w.xv,{className:"text-xs text-gray-600 mb-1 block",children:"Select Tool"}),(0,a.jsx)(C.default,{style:{width:"100%"},placeholder:"Select a tool to call",value:ep,onChange:e=>ex(e),options:(em[G[0]]||[]).map(e=>({value:e.name,label:e.name})),allowClear:!0,className:"rounded-md"})]}),G.length>0&&!G.includes("__all__")&&e2!==eA.KP.MCP&&tt.has(e2)&&(0,a.jsx)("div",{className:"mt-3 space-y-2",children:G.map(e=>{let t=F.find(t=>t.server_id===e),s=em[e]||[];return 0===s.length?null:(0,a.jsxs)("div",{className:"border rounded p-2",children:[(0,a.jsxs)(w.xv,{className:"text-xs text-gray-600 mb-1",children:["Limit tools for ",(null==t?void 0:t.alias)||(null==t?void 0:t.server_name)||e,":"]}),(0,a.jsx)(C.default,{mode:"multiple",size:"small",style:{width:"100%"},placeholder:"All tools (default)",value:eh[e]||[],onChange:t=>{ef(s=>({...s,[e]:t}))},options:s.map(e=>({value:e.name,label:e.name})),maxTagCount:2})]},e)})})]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(g.Z,{className:"mr-2"})," Vector Store",(0,a.jsx)(E.Z,{className:"ml-1",title:(0,a.jsxs)("span",{children:["Select vector store(s) to use for this LLM API call. You can set up your vector store"," ",(0,a.jsx)("a",{href:"?page=vector-stores",style:{color:"#1890ff"},children:"here"}),"."]}),children:(0,a.jsx)(x.Z,{})})]}),(0,a.jsx)(X.Z,{value:ti,onChange:tc,className:"mb-4",accessToken:t||""})]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(h.Z,{className:"mr-2"})," Guardrails",(0,a.jsx)(E.Z,{className:"ml-1",title:(0,a.jsxs)("span",{children:["Select guardrail(s) to use for this LLM API call. You can set up your guardrails"," ",(0,a.jsx)("a",{href:"?page=guardrails",style:{color:"#1890ff"},children:"here"}),"."]}),children:(0,a.jsx)(x.Z,{})})]}),(0,a.jsx)(U.Z,{value:td,onChange:tm,className:"mb-4",accessToken:t||""})]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)(w.xv,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,a.jsx)(h.Z,{className:"mr-2"})," Policies",(0,a.jsx)(E.Z,{className:"ml-1",title:(0,a.jsxs)("span",{children:["Select policy/policies to apply to this LLM API call. Policies define which guardrails are applied based on conditions. You can set up your policies"," ",(0,a.jsx)("a",{href:"?page=policies",style:{color:"#1890ff"},children:"here"}),"."]}),children:(0,a.jsx)(x.Z,{})})]}),(0,a.jsx)(D.Z,{value:tu,onChange:tp,className:"mb-4",accessToken:t||""})]}),e2===eA.KP.RESPONSES&&(0,a.jsx)("div",{children:(0,a.jsx)(eF,{accessToken:"session"===ev?t||"":eb,enabled:tW.enabled,onEnabledChange:tW.setEnabled,selectedContainerId:null,onContainerChange:()=>{},selectedModel:eO||""})})]})]}),(0,a.jsxs)("div",{className:"w-3/4 flex flex-col bg-white",children:[(0,a.jsxs)("div",{className:"p-4 border-b border-gray-200 flex justify-between items-center",children:[(0,a.jsx)(w.Dx,{className:"text-xl font-semibold mb-0",children:"Test Key"}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(w.zx,{onClick:()=>{eE.forEach(e=>{e.isAudio&&"string"==typeof e.content&&URL.revokeObjectURL(e.content)}),eZ([]),tg(null),tf(null),tB([]),sa(),sr(),sl(),so(),sessionStorage.removeItem("chatHistory"),sessionStorage.removeItem("messageTraceId"),sessionStorage.removeItem("responsesSessionId"),W.ZP.success("Chat history cleared.")},className:"bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300",icon:i.Z,children:"Clear Chat"}),(0,a.jsx)(w.zx,{onClick:()=>tM(!0),className:"bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300",icon:f.Z,children:"Get Code"})]})]}),(0,a.jsxs)("div",{className:"flex-1 overflow-auto p-4 pb-0",children:[0===eE.length&&(0,a.jsxs)("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[(0,a.jsx)(m.Z,{style:{fontSize:"48px",marginBottom:"16px"}}),(0,a.jsx)(w.xv,{children:"Start a conversation, generate an image, or handle audio"})]}),eE.map((e,s)=>(0,a.jsx)("div",{children:(0,a.jsx)("div",{className:"mb-4 ".concat("user"===e.role?"text-right":"text-left"),children:(0,a.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,a.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,a.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,a.jsx)(v.Z,{style:{fontSize:"12px",color:"#2563eb"}}):(0,a.jsx)(m.Z,{style:{fontSize:"12px",color:"#4b5563"}})}),(0,a.jsx)("strong",{className:"text-sm capitalize",children:e.role}),"assistant"===e.role&&e.model&&(0,a.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,a.jsx)(eX.Z,{reasoningContent:e.reasoningContent}),"assistant"===e.role&&s===eE.length-1&&tD.length>0&&(e2===eA.KP.RESPONSES||e2===eA.KP.CHAT)&&(0,a.jsx)("div",{className:"mb-3",children:(0,a.jsx)(eY,{events:tD})}),"assistant"===e.role&&e.searchResults&&(0,a.jsx)(e7.J,{searchResults:e.searchResults}),"assistant"===e.role&&s===eE.length-1&&tW.result&&e2===eA.KP.RESPONSES&&(0,a.jsx)(eU,{code:tW.result.code,containerId:tW.result.containerId,annotations:tW.result.annotations,accessToken:"session"===ev?t||"":eb}),(0,a.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,a.jsx)("img",{src:"string"==typeof e.content?e.content:"",alt:"Generated image",className:"max-w-full rounded-md border border-gray-200 shadow-sm",style:{maxHeight:"500px"}}):e.isAudio?(0,a.jsx)(ek,{message:e}):(0,a.jsxs)(a.Fragment,{children:[e2===eA.KP.RESPONSES&&(0,a.jsx)(e4,{message:e}),e2===eA.KP.CHAT&&(0,a.jsx)(eT.Z,{message:e}),(0,a.jsx)(L.UG,{components:{code(e){let{node:t,inline:s,className:r,children:l,...o}=e,n=/language-(\w+)/.exec(r||"");return!s&&n?(0,a.jsx)(M.Z,{style:O.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",wrapLines:!0,wrapLongLines:!0,...o,children:String(l).replace(/\n$/,"")}):(0,a.jsx)("code",{className:"".concat(r," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),style:{wordBreak:"break-word"},...o,children:l})},pre:e=>{let{node:t,...s}=e;return(0,a.jsx)("pre",{style:{overflowX:"auto",maxWidth:"100%"},...s})}},children:"string"==typeof e.content?e.content:""}),e.image&&(0,a.jsx)("div",{className:"mt-3",children:(0,a.jsx)("img",{src:e.image.url,alt:"Generated image",className:"max-w-full rounded-md border border-gray-200 shadow-sm",style:{maxHeight:"500px"}})})]}),"assistant"===e.role&&(e.timeToFirstToken||e.totalLatency||e.usage)&&!e.a2aMetadata&&(0,a.jsx)(e$.Z,{timeToFirstToken:e.timeToFirstToken,totalLatency:e.totalLatency,usage:e.usage,toolName:e.toolName}),"assistant"===e.role&&e.a2aMetadata&&(0,a.jsx)(ew,{a2aMetadata:e.a2aMetadata,timeToFirstToken:e.timeToFirstToken,totalLatency:e.totalLatency})]})]})})},s)),e5&&tD.length>0&&(e2===eA.KP.RESPONSES||e2===eA.KP.CHAT)&&eE.length>0&&"user"===eE[eE.length-1].role&&(0,a.jsx)("div",{className:"text-left mb-4",children:(0,a.jsxs)("div",{className:"inline-block max-w-[80%] rounded-lg shadow-sm p-3.5 px-4",style:{backgroundColor:"#ffffff",border:"1px solid #f0f0f0",textAlign:"left"},children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,a.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full mr-1",style:{backgroundColor:"#f5f5f5"},children:(0,a.jsx)(m.Z,{style:{fontSize:"12px",color:"#4b5563"}})}),(0,a.jsx)("strong",{className:"text-sm capitalize",children:"Assistant"})]}),(0,a.jsx)(eY,{events:tD})]})}),e5&&(0,a.jsx)("div",{className:"flex justify-center items-center my-4",children:(0,a.jsx)(I.Z,{indicator:si})}),(0,a.jsx)("div",{ref:tV,style:{height:"1px"}})]}),(0,a.jsxs)("div",{className:"p-4 border-t border-gray-200 bg-white",children:[e2===eA.KP.IMAGE_EDITS&&(0,a.jsx)("div",{className:"mb-4",children:0===tb.length?(0,a.jsxs)(te,{beforeUpload:st,accept:"image/*",showUploadList:!1,children:[(0,a.jsx)("p",{className:"ant-upload-drag-icon",children:(0,a.jsx)(y.Z,{style:{fontSize:"24px",color:"#666"}})}),(0,a.jsx)("p",{className:"ant-upload-text text-sm",children:"Click or drag images to upload"}),(0,a.jsx)("p",{className:"ant-upload-hint text-xs text-gray-500",children:"Support for PNG, JPG, JPEG formats. Multiple images supported."})]}):(0,a.jsxs)("div",{className:"flex flex-wrap gap-2",children:[tb.map((e,t)=>(0,a.jsxs)("div",{className:"relative inline-block",children:[(0,a.jsx)("img",{src:tN[t]||"",alt:"Upload preview ".concat(t+1),className:"max-w-32 max-h-32 rounded-md border border-gray-200 object-cover"}),(0,a.jsx)("button",{className:"absolute top-1 right-1 bg-white shadow-sm border border-gray-200 rounded px-1 py-1 text-red-500 hover:bg-red-50 text-xs",onClick:()=>ss(t),children:(0,a.jsx)(b.Z,{})})]},t)),(0,a.jsxs)("div",{className:"flex items-center justify-center w-32 h-32 border-2 border-dashed border-gray-300 rounded-md hover:border-gray-400 cursor-pointer",onClick:()=>{var e;return null===(e=document.getElementById("additional-image-upload"))||void 0===e?void 0:e.click()},children:[(0,a.jsxs)("div",{className:"text-center",children:[(0,a.jsx)(y.Z,{style:{fontSize:"24px",color:"#666"}}),(0,a.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Add more"})]}),(0,a.jsx)("input",{id:"additional-image-upload",type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:e=>{Array.from(e.target.files||[]).forEach(e=>st(e))}})]})]})}),e2===eA.KP.TRANSCRIPTION&&(0,a.jsx)("div",{className:"mb-4",children:tZ?(0,a.jsxs)("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 flex-1",children:[(0,a.jsx)(d.Z,{style:{fontSize:"20px",color:"#666"}}),(0,a.jsx)("span",{className:"text-sm font-medium",children:tZ.name}),(0,a.jsxs)("span",{className:"text-xs text-gray-500",children:["(",(tZ.size/1024/1024).toFixed(2)," MB)"]})]}),(0,a.jsxs)("button",{className:"bg-white shadow-sm border border-gray-200 rounded px-2 py-1 text-red-500 hover:bg-red-50 text-xs",onClick:so,children:[(0,a.jsx)(b.Z,{})," Remove"]})]}):(0,a.jsxs)(te,{beforeUpload:e=>(tT(e),!1),accept:"audio/*,.mp3,.mp4,.mpeg,.mpga,.m4a,.wav,.webm",showUploadList:!1,children:[(0,a.jsx)("p",{className:"ant-upload-drag-icon",children:(0,a.jsx)(d.Z,{style:{fontSize:"24px",color:"#666"}})}),(0,a.jsx)("p",{className:"ant-upload-text text-sm",children:"Click or drag audio file to upload"}),(0,a.jsx)("p",{className:"ant-upload-hint text-xs text-gray-500",children:"Support for MP3, MP4, MPEG, MPGA, M4A, WAV, WEBM formats. Max file size: 25 MB."})]})}),e2===eA.KP.RESPONSES&&tS&&(0,a.jsx)("div",{className:"mb-2",children:(0,a.jsxs)("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[(0,a.jsx)("div",{className:"relative inline-block",children:tS.name.toLowerCase().endsWith(".pdf")?(0,a.jsx)("div",{className:"w-10 h-10 rounded-md bg-red-500 flex items-center justify-center",children:(0,a.jsx)(j.Z,{style:{fontSize:"16px",color:"white"}})}):(0,a.jsx)("img",{src:tP||"",alt:"Upload preview",className:"w-10 h-10 rounded-md border border-gray-200 object-cover"})}),(0,a.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,a.jsx)("div",{className:"text-sm font-medium text-gray-900 truncate",children:tS.name}),(0,a.jsx)("div",{className:"text-xs text-gray-500",children:tS.name.toLowerCase().endsWith(".pdf")?"PDF":"Image"})]}),(0,a.jsx)("button",{className:"flex items-center justify-center w-6 h-6 text-gray-400 hover:text-gray-600 hover:bg-gray-200 rounded-full transition-colors",onClick:sr,children:(0,a.jsx)(b.Z,{style:{fontSize:"12px"}})})]})}),e2===eA.KP.CHAT&&tk&&(0,a.jsx)("div",{className:"mb-2",children:(0,a.jsxs)("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[(0,a.jsx)("div",{className:"relative inline-block",children:tk.name.toLowerCase().endsWith(".pdf")?(0,a.jsx)("div",{className:"w-10 h-10 rounded-md bg-red-500 flex items-center justify-center",children:(0,a.jsx)(j.Z,{style:{fontSize:"16px",color:"white"}})}):(0,a.jsx)("img",{src:tE||"",alt:"Upload preview",className:"w-10 h-10 rounded-md border border-gray-200 object-cover"})}),(0,a.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,a.jsx)("div",{className:"text-sm font-medium text-gray-900 truncate",children:tk.name}),(0,a.jsx)("div",{className:"text-xs text-gray-500",children:tk.name.toLowerCase().endsWith(".pdf")?"PDF":"Image"})]}),(0,a.jsx)("button",{className:"flex items-center justify-center w-6 h-6 text-gray-400 hover:text-gray-600 hover:bg-gray-200 rounded-full transition-colors",onClick:sl,children:(0,a.jsx)(b.Z,{style:{fontSize:"12px"}})})]})}),e2===eA.KP.RESPONSES&&tW.enabled&&(0,a.jsxs)("div",{className:"mb-2 space-y-2",children:[(0,a.jsxs)("div",{className:"px-3 py-2 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border border-blue-200 flex items-center justify-between",children:[(0,a.jsx)("div",{className:"flex items-center gap-2",children:e5?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(r.Z,{className:"text-blue-500",spin:!0}),(0,a.jsx)("span",{className:"text-sm text-blue-700 font-medium",children:"Running Python code..."})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(f.Z,{className:"text-blue-500"}),(0,a.jsx)("span",{className:"text-sm text-blue-700 font-medium",children:"Code Interpreter Active"})]})}),(0,a.jsx)("button",{className:"text-xs text-blue-500 hover:text-blue-700",onClick:()=>tW.setEnabled(!1),children:"Disable"})]}),!e5&&(0,a.jsx)("div",{className:"flex flex-wrap gap-2",children:["Generate sample sales data CSV and create a chart","Create a PNG bar chart comparing AI gateway providers including LiteLLM","Generate a CSV of LLM pricing data and visualize it as a line chart"].map((e,t)=>(0,a.jsx)("button",{className:"text-xs px-3 py-1.5 bg-white border border-gray-200 rounded-full hover:bg-blue-50 hover:border-blue-300 hover:text-blue-600 transition-colors",onClick:()=>eP(e),children:e},t))})]}),0===eE.length&&!e5&&e2!==eA.KP.MCP&&(0,a.jsx)("div",{className:"flex items-center gap-2 mb-3 overflow-x-auto",children:(e2===eA.KP.A2A_AGENTS?["What can you help me with?","Tell me about yourself","What tasks can you perform?"]:["Write me a poem","Explain quantum computing","Draft a polite email requesting a meeting"]).map(e=>(0,a.jsx)("button",{type:"button",className:"shrink-0 rounded-full border border-gray-200 px-3 py-1 text-xs font-medium text-gray-600 transition-colors hover:bg-blue-50 hover:border-blue-300 hover:text-blue-600 cursor-pointer",onClick:()=>eP(e),children:e},e))}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsxs)("div",{className:"flex items-center flex-1 bg-white border border-gray-300 rounded-xl px-3 py-1 min-h-[44px]",children:[(0,a.jsxs)("div",{className:"flex-shrink-0 mr-2 flex items-center gap-1",children:[e2===eA.KP.RESPONSES&&!tS&&(0,a.jsx)(e6,{responsesUploadedImage:tS,responsesImagePreviewUrl:tP,onImageUpload:e=>(t_(e),tC(URL.createObjectURL(e)),!1),onRemoveImage:sr}),e2===eA.KP.CHAT&&!tk&&(0,a.jsx)(eL.Z,{chatUploadedImage:tk,chatImagePreviewUrl:tE,onImageUpload:e=>(tA(e),tI(URL.createObjectURL(e)),!1),onRemoveImage:sl}),e2===eA.KP.RESPONSES&&(0,a.jsx)(E.Z,{title:tW.enabled?"Code Interpreter enabled (click to disable)":"Enable Code Interpreter",children:(0,a.jsx)("button",{className:"p-1.5 rounded-md transition-colors ".concat(tW.enabled?"bg-blue-100 text-blue-600":"text-gray-400 hover:text-gray-600 hover:bg-gray-100"),onClick:()=>{tW.toggle(),tW.enabled||W.ZP.success("Code Interpreter enabled!")},children:(0,a.jsx)(f.Z,{style:{fontSize:"16px"}})})})]}),e2===eA.KP.MCP&&1===G.length&&"__all__"!==G[0]&&ep?(0,a.jsx)("div",{className:"flex-1 overflow-y-auto max-h-48 min-h-[44px] p-2 border border-gray-200 rounded-lg bg-gray-50/50",children:(()=>{let e=(em[G[0]]||[]).find(e=>e.name===ep);return e?(0,a.jsx)(J,{ref:eg,tool:e,className:"space-y-2"}):(0,a.jsx)("div",{className:"flex items-center justify-center h-10 text-sm text-gray-500",children:"Loading tool schema..."})})()}):(0,a.jsx)(e9,{value:e_,onChange:e=>eP(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),sn())},placeholder:e2===eA.KP.CHAT||e2===eA.KP.EMBEDDINGS||e2===eA.KP.RESPONSES||e2===eA.KP.ANTHROPIC_MESSAGES?"Type your message... (Shift+Enter for new line)":e2===eA.KP.A2A_AGENTS?"Send a message to the A2A agent...":e2===eA.KP.IMAGE_EDITS?"Describe how you want to edit the image...":e2===eA.KP.SPEECH?"Enter text to convert to speech...":e2===eA.KP.TRANSCRIPTION?"Optional: Add context or prompt for transcription...":"Describe the image you want to generate...",disabled:e5,className:"flex-1",autoSize:{minRows:1,maxRows:4},style:{resize:"none",border:"none",boxShadow:"none",background:"transparent",padding:"4px 0",fontSize:"14px",lineHeight:"20px"}}),(0,a.jsx)(w.zx,{onClick:sn,disabled:e5||(e2===eA.KP.MCP?!(1===G.length&&"__all__"!==G[0]&&ep):e2===eA.KP.TRANSCRIPTION?!tZ:!e_.trim()),className:"flex-shrink-0 ml-2 !w-8 !h-8 !min-w-8 !p-0 !rounded-full !bg-blue-600 hover:!bg-blue-700 disabled:!bg-gray-300 !border-none !text-white disabled:!text-gray-500 !flex !items-center !justify-center",children:(0,a.jsx)(N.Z,{style:{fontSize:"14px"}})})]}),e5&&(0,a.jsx)(w.zx,{onClick:()=>{ta.current&&(ta.current.abort(),ta.current=null,ts(!1),W.ZP.info("Request cancelled"))},className:"bg-red-50 hover:bg-red-100 text-red-600 border-red-200",icon:b.Z,children:"Cancel"})]})]})]})]})}),(0,a.jsxs)(Z.Z,{title:"Generated Code",visible:tL,onCancel:()=>tM(!1),footer:null,width:800,children:[(0,a.jsxs)("div",{className:"flex justify-between items-end my-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)(w.xv,{className:"font-medium block mb-1 text-gray-700",children:"SDK Type"}),(0,a.jsx)(C.default,{value:tK,onChange:e=>tU(e),style:{width:150},options:[{value:"openai",label:"OpenAI SDK"},{value:"azure",label:"Azure SDK"}]})]}),(0,a.jsx)(k.ZP,{onClick:()=>{navigator.clipboard.writeText(tO),W.ZP.success("Copied to clipboard!")},children:"Copy to Clipboard"})]}),(0,a.jsx)(M.Z,{language:"python",style:O.Z,wrapLines:!0,wrapLongLines:!0,className:"rounded-md",customStyle:{maxHeight:"60vh",overflowY:"auto"},children:tO})]})]})}},94331:function(e,t,s){var a=s(57437),r=s(2265),l=s(5545),o=s(62831),n=s(17906),i=s(94263),c=s(83322),d=s(70464),m=s(77565);t.Z=e=>{let{reasoningContent:t}=e,[s,u]=(0,r.useState)(!0);return t?(0,a.jsxs)("div",{className:"reasoning-content mt-1 mb-2",children:[(0,a.jsxs)(l.ZP,{type:"text",className:"flex items-center text-xs text-gray-500 hover:text-gray-700",onClick:()=>u(!s),icon:(0,a.jsx)(c.Z,{}),children:[s?"Hide reasoning":"Show reasoning",s?(0,a.jsx)(d.Z,{className:"ml-1"}):(0,a.jsx)(m.Z,{className:"ml-1"})]}),s&&(0,a.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-700",children:(0,a.jsx)(o.UG,{components:{code(e){let{node:t,inline:s,className:r,children:l,...o}=e,c=/language-(\w+)/.exec(r||"");return!s&&c?(0,a.jsx)(n.Z,{style:i.Z,language:c[1],PreTag:"div",className:"rounded-md my-2",...o,children:String(l).replace(/\n$/,"")}):(0,a.jsx)("code",{className:"".concat(r," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),...o,children:l})}},children:t})})]}):null}},38398:function(e,t,s){var a=s(57437);s(2265);var r=s(99981),l=s(5540),o=s(71282),n=s(11741),i=s(83322),c=s(16601),d=s(62670),m=s(58630);t.Z=e=>{let{timeToFirstToken:t,totalLatency:s,usage:u,toolName:p}=e;return t||s||u?(0,a.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!==t&&(0,a.jsx)(r.Z,{title:"Time to first token",children:(0,a.jsxs)("div",{className:"flex items-center",children:[(0,a.jsx)(l.Z,{className:"mr-1"}),(0,a.jsxs)("span",{children:["TTFT: ",(t/1e3).toFixed(2),"s"]})]})}),void 0!==s&&(0,a.jsx)(r.Z,{title:"Total latency",children:(0,a.jsxs)("div",{className:"flex items-center",children:[(0,a.jsx)(l.Z,{className:"mr-1"}),(0,a.jsxs)("span",{children:["Total Latency: ",(s/1e3).toFixed(2),"s"]})]})}),(null==u?void 0:u.promptTokens)!==void 0&&(0,a.jsx)(r.Z,{title:"Prompt tokens",children:(0,a.jsxs)("div",{className:"flex items-center",children:[(0,a.jsx)(o.Z,{className:"mr-1"}),(0,a.jsxs)("span",{children:["In: ",u.promptTokens]})]})}),(null==u?void 0:u.completionTokens)!==void 0&&(0,a.jsx)(r.Z,{title:"Completion tokens",children:(0,a.jsxs)("div",{className:"flex items-center",children:[(0,a.jsx)(n.Z,{className:"mr-1"}),(0,a.jsxs)("span",{children:["Out: ",u.completionTokens]})]})}),(null==u?void 0:u.reasoningTokens)!==void 0&&(0,a.jsx)(r.Z,{title:"Reasoning tokens",children:(0,a.jsxs)("div",{className:"flex items-center",children:[(0,a.jsx)(i.Z,{className:"mr-1"}),(0,a.jsxs)("span",{children:["Reasoning: ",u.reasoningTokens]})]})}),(null==u?void 0:u.totalTokens)!==void 0&&(0,a.jsx)(r.Z,{title:"Total tokens",children:(0,a.jsxs)("div",{className:"flex items-center",children:[(0,a.jsx)(c.Z,{className:"mr-1"}),(0,a.jsxs)("span",{children:["Total: ",u.totalTokens]})]})}),(null==u?void 0:u.cost)!==void 0&&(0,a.jsx)(r.Z,{title:"Cost",children:(0,a.jsxs)("div",{className:"flex items-center",children:[(0,a.jsx)(d.Z,{className:"mr-1"}),(0,a.jsxs)("span",{children:["$",u.cost.toFixed(6)]})]})}),p&&(0,a.jsx)(r.Z,{title:"Tool used",children:(0,a.jsxs)("div",{className:"flex items-center",children:[(0,a.jsx)(m.Z,{className:"mr-1"}),(0,a.jsxs)("span",{children:["Tool: ",p]})]})})]}):null}},33152:function(e,t,s){s.d(t,{J:function(){return d}});var a=s(57437),r=s(2265),l=s(5545),o=s(44625),n=s(70464),i=s(77565),c=s(38434);function d(e){let{searchResults:t}=e,[s,d]=(0,r.useState)(!0),[m,u]=(0,r.useState)({});if(!t||0===t.length)return null;let p=(e,t)=>{let s="".concat(e,"-").concat(t);u(e=>({...e,[s]:!e[s]}))},x=t.reduce((e,t)=>e+t.data.length,0);return(0,a.jsxs)("div",{className:"search-results-content mt-1 mb-2",children:[(0,a.jsxs)(l.ZP,{type:"text",className:"flex items-center text-xs text-gray-500 hover:text-gray-700",onClick:()=>d(!s),icon:(0,a.jsx)(o.Z,{}),children:[s?"Hide sources":"Show sources (".concat(x,")"),s?(0,a.jsx)(n.Z,{className:"ml-1"}):(0,a.jsx)(i.Z,{className:"ml-1"})]}),s&&(0,a.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm",children:(0,a.jsx)("div",{className:"space-y-3",children:t.map((e,t)=>(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"text-xs text-gray-600 mb-2 flex items-center gap-2",children:[(0,a.jsx)("span",{className:"font-medium",children:"Query:"}),(0,a.jsxs)("span",{className:"italic",children:['"',e.search_query,'"']}),(0,a.jsx)("span",{className:"text-gray-400",children:"•"}),(0,a.jsxs)("span",{className:"text-gray-500",children:[e.data.length," result",1!==e.data.length?"s":""]})]}),(0,a.jsx)("div",{className:"space-y-2",children:e.data.map((e,s)=>{let r=m["".concat(t,"-").concat(s)]||!1;return(0,a.jsxs)("div",{className:"border border-gray-200 rounded-md overflow-hidden bg-white",children:[(0,a.jsx)("div",{className:"flex items-center justify-between p-2 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>p(t,s),children:(0,a.jsxs)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(0,a.jsx)("svg",{className:"w-4 h-4 text-gray-400 transition-transform flex-shrink-0 ".concat(r?"transform rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,a.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),(0,a.jsx)(c.Z,{className:"text-gray-400 flex-shrink-0",style:{fontSize:"12px"}}),(0,a.jsx)("span",{className:"text-xs font-medium text-gray-700 truncate",children:e.filename||e.file_id||"Result ".concat(s+1)}),(0,a.jsx)("span",{className:"text-xs px-2 py-0.5 rounded bg-blue-100 text-blue-700 font-mono flex-shrink-0",children:e.score.toFixed(3)})]})}),r&&(0,a.jsx)("div",{className:"border-t border-gray-200 bg-white",children:(0,a.jsxs)("div",{className:"p-3 space-y-2",children:[e.content.map((e,t)=>(0,a.jsx)("div",{children:(0,a.jsx)("div",{className:"text-xs font-mono bg-gray-50 p-2 rounded text-gray-800 whitespace-pre-wrap break-words",children:e.text})},t)),e.attributes&&Object.keys(e.attributes).length>0&&(0,a.jsxs)("div",{className:"mt-2 pt-2 border-t border-gray-100",children:[(0,a.jsx)("div",{className:"text-xs text-gray-500 mb-1 font-medium",children:"Metadata:"}),(0,a.jsx)("div",{className:"space-y-1",children:Object.entries(e.attributes).map(e=>{let[t,s]=e;return(0,a.jsxs)("div",{className:"text-xs flex gap-2",children:[(0,a.jsxs)("span",{className:"text-gray-500 font-medium",children:[t,":"]}),(0,a.jsx)("span",{className:"text-gray-700 font-mono break-all",children:String(s)})]},t)})})]})]})})]},s)})})]},t))})})]})}},26832:function(e,t,s){s.d(t,{O:function(){return o},m:function(){return n}});var a=s(93837),r=s(19250);let l=e=>{if(!e)return;let t={};if(e.id&&(t.taskId=e.id),e.contextId&&(t.contextId=e.contextId),e.status){var s;if(t.status={state:e.status.state,timestamp:e.status.timestamp},null===(s=e.status.message)||void 0===s?void 0:s.parts){let s=e.status.message.parts.filter(e=>"text"===e.kind&&e.text).map(e=>e.text).join(" ");s&&(t.status.message=s)}}return e.metadata&&"object"==typeof e.metadata&&(t.metadata=e.metadata),Object.keys(t).length>0?t:void 0},o=async(e,t,s,o,n,i,c,d,m,u)=>{let p=m||(0,r.getProxyBaseUrl)(),x=p?"".concat(p,"/a2a/").concat(e,"/message/send"):"/a2a/".concat(e,"/message/send"),g={jsonrpc:"2.0",id:(0,a.Z)(),method:"message/send",params:{message:{kind:"message",messageId:(0,a.Z)().replace(/-/g,""),role:"user",parts:[{kind:"text",text:t}]}}};u&&u.length>0&&(g.params.metadata={guardrails:u});let h=performance.now();try{var f,v,y;let t=await fetch(x,{method:"POST",headers:{[(0,r.getGlobalLitellmHeaderName)()]:"Bearer ".concat(o),"Content-Type":"application/json"},body:JSON.stringify(g),signal:n}),a=performance.now()-h;if(i&&i(a),!t.ok){let e=await t.json();throw Error((null===(f=e.error)||void 0===f?void 0:f.message)||e.detail||"HTTP ".concat(t.status))}let m=await t.json(),u=performance.now()-h;if(c&&c(u),m.error)throw Error(m.error.message);let p=m.result;if(p){let t="",a=l(p);if(a&&d&&d(a),p.artifacts&&Array.isArray(p.artifacts)){for(let e of p.artifacts)if(e.parts&&Array.isArray(e.parts))for(let s of e.parts)"text"===s.kind&&s.text&&(t+=s.text)}else if(p.parts&&Array.isArray(p.parts))for(let e of p.parts)"text"===e.kind&&e.text&&(t+=e.text);else if(null===(y=p.status)||void 0===y?void 0:null===(v=y.message)||void 0===v?void 0:v.parts)for(let e of p.status.message.parts)"text"===e.kind&&e.text&&(t+=e.text);t?s(t,"a2a_agent/".concat(e)):(console.warn("Could not extract text from A2A response, showing raw JSON:",p),s(JSON.stringify(p,null,2),"a2a_agent/".concat(e)))}}catch(e){if(null==n?void 0:n.aborted){console.log("A2A request was cancelled");return}throw console.error("A2A send message error:",e),e}},n=async(e,t,s,o,n,i,c,d,m)=>{let u;let p=m||(0,r.getProxyBaseUrl)(),x=p?"".concat(p,"/a2a/").concat(e):"/a2a/".concat(e),g=(0,a.Z)(),h=(0,a.Z)().replace(/-/g,""),f=performance.now(),v=!1,y="";try{var b,j;let a=await fetch(x,{method:"POST",headers:{[(0,r.getGlobalLitellmHeaderName)()]:"Bearer ".concat(o),"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:g,method:"message/stream",params:{message:{kind:"message",messageId:h,role:"user",parts:[{kind:"text",text:t}]}}}),signal:n});if(!a.ok){let e=await a.json();throw Error((null===(j=e.error)||void 0===j?void 0:j.message)||e.detail||"HTTP ".concat(a.status))}let m=null===(b=a.body)||void 0===b?void 0:b.getReader();if(!m)throw Error("No response body");let p=new TextDecoder,N="",w=!1;for(;!w;){let t=await m.read();w=t.done;let a=t.value;if(w)break;let r=(N+=p.decode(a,{stream:!0})).split("\n");for(let t of(N=r.pop()||"",r))if(t.trim())try{let a=JSON.parse(t);if(!v){v=!0;let e=performance.now()-f;i&&i(e)}let r=a.result;if(r){let t=l(r);t&&(u={...u,...t});let a=r.kind;if("artifact-update"===a&&r.artifact){let t=r.artifact;if(t.parts&&Array.isArray(t.parts))for(let a of t.parts)"text"===a.kind&&a.text&&(y+=a.text,s(y,"a2a_agent/".concat(e)))}else if(r.artifacts&&Array.isArray(r.artifacts)){for(let t of r.artifacts)if(t.parts&&Array.isArray(t.parts))for(let a of t.parts)"text"===a.kind&&a.text&&(y+=a.text,s(y,"a2a_agent/".concat(e)))}else if("status-update"===a);else if(r.parts&&Array.isArray(r.parts))for(let t of r.parts)"text"===t.kind&&t.text&&(y+=t.text,s(y,"a2a_agent/".concat(e)))}if(a.error){let e=a.error.message||"Unknown A2A error";throw Error(e)}}catch(e){if(e instanceof Error&&e.message&&!e.message.includes("JSON"))throw e;t.trim().length>0&&console.warn("Failed to parse A2A streaming chunk:",t,e)}}let S=performance.now()-f;c&&c(S),u&&d&&d(u)}catch(e){if(null==n?void 0:n.aborted){console.log("A2A streaming request was cancelled");return}throw console.error("A2A stream message error:",e),e}}},95459:function(e,t,s){s.d(t,{n:function(){return l}});var a=s(7271),r=s(19250);async function l(e,t,s,l,o,n,i,c,d,m,u,p,x,g,h,f,v,y,b,j,N,w,S){console.log=function(){},console.log("isLocal:",!1);let _=j||(0,r.getProxyBaseUrl)(),P={};o&&o.length>0&&(P["x-litellm-tags"]=o.join(","));let C=new a.ZP.OpenAI({apiKey:l,baseURL:_,dangerouslyAllowBrowser:!0,defaultHeaders:P});try{let a;let r=Date.now(),l=!1,o={},j=!1,_=[];for await(let b of(g&&g.length>0&&(g.includes("__all__")?_.push({type:"mcp",server_label:"litellm",server_url:"litellm_proxy/mcp",require_approval:"never"}):g.forEach(e=>{let t=null==N?void 0:N.find(t=>t.server_id===e),s=(null==t?void 0:t.alias)||(null==t?void 0:t.server_name)||e,a=(null==w?void 0:w[e])||[];_.push({type:"mcp",server_label:"litellm",server_url:"litellm_proxy/mcp/".concat(s),require_approval:"never",...a.length>0?{allowed_tools:a}:{}})})),await C.chat.completions.create({model:s,stream:!0,stream_options:{include_usage:!0},litellm_trace_id:m,messages:e,...u?{vector_store_ids:u}:{},...p?{guardrails:p}:{},...x?{policies:x}:{},..._.length>0?{tools:_,tool_choice:"auto"}:{},...void 0!==v?{temperature:v}:{},...void 0!==y?{max_tokens:y}:{}},{signal:n}))){var k,A,E,I,Z,T,L,M,O;console.log("Stream chunk:",b);let e=null===(k=b.choices[0])||void 0===k?void 0:k.delta;if(console.log("Delta content:",null===(E=b.choices[0])||void 0===E?void 0:null===(A=E.delta)||void 0===A?void 0:A.content),console.log("Delta reasoning content:",null==e?void 0:e.reasoning_content),!l&&((null===(Z=b.choices[0])||void 0===Z?void 0:null===(I=Z.delta)||void 0===I?void 0:I.content)||e&&e.reasoning_content)&&(l=!0,a=Date.now()-r,console.log("First token received! Time:",a,"ms"),c?(console.log("Calling onTimingData with:",a),c(a)):console.log("onTimingData callback is not defined!")),null===(L=b.choices[0])||void 0===L?void 0:null===(T=L.delta)||void 0===T?void 0:T.content){let e=b.choices[0].delta.content;t(e,b.model)}if(e&&e.image&&h&&(console.log("Image generated:",e.image),h(e.image.url,b.model)),e&&e.reasoning_content){let t=e.reasoning_content;i&&i(t)}if(e&&(null===(M=e.provider_specific_fields)||void 0===M?void 0:M.search_results)&&f&&(console.log("Search results found:",e.provider_specific_fields.search_results),f(e.provider_specific_fields.search_results)),e&&e.provider_specific_fields){let t=e.provider_specific_fields;if(t.mcp_list_tools&&!o.mcp_list_tools&&(o.mcp_list_tools=t.mcp_list_tools,S&&!j)){j=!0;let e={type:"response.output_item.done",item_id:"mcp_list_tools",item:{type:"mcp_list_tools",tools:t.mcp_list_tools.map(e=>{var t,s,a;return{name:(null===(t=e.function)||void 0===t?void 0:t.name)||e.name||"",description:(null===(s=e.function)||void 0===s?void 0:s.description)||e.description||"",input_schema:(null===(a=e.function)||void 0===a?void 0:a.parameters)||e.input_schema||{}}})},timestamp:Date.now()};S(e),console.log("MCP list_tools event sent:",e)}t.mcp_tool_calls&&(o.mcp_tool_calls=t.mcp_tool_calls),t.mcp_call_results&&(o.mcp_call_results=t.mcp_call_results),(t.mcp_list_tools||t.mcp_tool_calls||t.mcp_call_results)&&console.log("MCP metadata found in chunk:",{mcp_list_tools:t.mcp_list_tools?"present":"absent",mcp_tool_calls:t.mcp_tool_calls?"present":"absent",mcp_call_results:t.mcp_call_results?"present":"absent"})}if(b.usage&&d){console.log("Usage data found:",b.usage);let e={completionTokens:b.usage.completion_tokens,promptTokens:b.usage.prompt_tokens,totalTokens:b.usage.total_tokens};(null===(O=b.usage.completion_tokens_details)||void 0===O?void 0:O.reasoning_tokens)&&(e.reasoningTokens=b.usage.completion_tokens_details.reasoning_tokens),void 0!==b.usage.cost&&null!==b.usage.cost&&(e.cost=parseFloat(b.usage.cost)),d(e)}}S&&(o.mcp_tool_calls||o.mcp_call_results)&&o.mcp_tool_calls&&o.mcp_tool_calls.length>0&&o.mcp_tool_calls.forEach((e,t)=>{var s,a,r,l;let n=(null===(s=e.function)||void 0===s?void 0:s.name)||e.name||"",i=(null===(a=e.function)||void 0===a?void 0:a.arguments)||e.arguments||"{}",c=(null===(r=o.mcp_call_results)||void 0===r?void 0:r.find(t=>t.tool_call_id===e.id||t.tool_call_id===e.call_id))||(null===(l=o.mcp_call_results)||void 0===l?void 0:l[t]),d={type:"response.output_item.done",item:{type:"mcp_call",name:n,arguments:"string"==typeof i?i:JSON.stringify(i),output:(null==c?void 0:c.result)?"string"==typeof c.result?c.result:JSON.stringify(c.result):void 0},item_id:e.id||e.call_id,timestamp:Date.now()};S(d),console.log("MCP call event sent:",d)});let P=Date.now();b&&b(P-r)}catch(e){throw(null==n?void 0:n.aborted)&&console.log("Chat completion request was cancelled"),e}}},91643:function(e,t,s){s.d(t,{o:function(){return r}});var a=s(19250);let r=async(e,t)=>{try{let s=t||(0,a.getProxyBaseUrl)(),r=await fetch(s?"".concat(s,"/v1/agents"):"/v1/agents",{method:"GET",headers:{[(0,a.getGlobalLitellmHeaderName)()]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.json();throw Error(e.detail||"Failed to fetch agents")}let l=await r.json();return console.log("Fetched agents:",l),l.sort((e,t)=>{let s=e.agent_name||e.agent_id,a=t.agent_name||t.agent_id;return s.localeCompare(a)}),l}catch(e){throw console.error("Error fetching agents:",e),e}}},99020:function(e,t,s){var a=s(57437),r=s(2265),l=s(37592),o=s(19250);t.Z=e=>{let{onChange:t,value:s,className:n,accessToken:i}=e,[c,d]=(0,r.useState)([]),[m,u]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(i)try{let e=await (0,o.tagListCall)(i);console.log("List tags response:",e),d(Object.values(e))}catch(e){console.error("Error fetching tags:",e)}finally{u(!1)}})()},[i]),(0,a.jsx)(l.default,{mode:"tags",showSearch:!0,placeholder:"Select or create tags",onChange:t,value:s,loading:m,className:n,options:c.map(e=>({label:e.name,value:e.name,title:e.description||e.name})),optionFilterProp:"label",tokenSeparators:[","],maxTagCount:"responsive",allowClear:!0,style:{width:"100%"}})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/2063-6862ac626abaa804.js b/litellm/proxy/_experimental/out/_next/static/chunks/2063-6862ac626abaa804.js new file mode 100644 index 00000000000..304850be79a --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/2063-6862ac626abaa804.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2063],{92063:function(e,l,t){t.d(l,{Z:function(){return l5}});var s=t(57437),a=t(19250),r=t(11713),i=t(90246),n=t(80443);let o=(0,i.n)("credentials"),d=()=>{let{accessToken:e}=(0,n.Z)();return(0,r.a)({queryKey:o.list({}),queryFn:async()=>await (0,a.credentialListCall)(e),enabled:!!e})},c=(0,i.n)("modelCostMap"),m=()=>(0,r.a)({queryKey:c.list({}),queryFn:async()=>await (0,a.modelCostMap)(),staleTime:6e4,gcTime:6e4});var u=t(52178),h=t(55584),x=t(47359),p=t(71594),g=t(24525),f=t(2265),j=t(19130),v=t(73705),_=t(5545),y=t(44633),b=t(86462),N=t(3837),w=t(49084);let Z=e=>{let{sortState:l,onSortChange:t}=e,a=[{key:"asc",label:"Ascending",icon:(0,s.jsx)(y.Z,{className:"h-4 w-4"})},{key:"desc",label:"Descending",icon:(0,s.jsx)(b.Z,{className:"h-4 w-4"})},{key:"reset",label:"Reset",icon:(0,s.jsx)(N.Z,{className:"h-4 w-4"})}];return(0,s.jsx)(v.Z,{menu:{items:a,onClick:e=>{let{key:l}=e;"asc"===l?t("asc"):"desc"===l?t("desc"):"reset"===l&&t(!1)},selectable:!0,selectedKeys:l?[l]:[]},trigger:["click"],autoAdjustOverflow:!0,children:(0,s.jsx)(_.ZP,{type:"text",onClick:e=>e.stopPropagation(),icon:"asc"===l?(0,s.jsx)(y.Z,{className:"h-4 w-4"}):"desc"===l?(0,s.jsx)(b.Z,{className:"h-4 w-4"}):(0,s.jsx)(w.Z,{className:"h-4 w-4"}),className:l?"text-blue-500 hover:text-blue-600":"text-gray-400 hover:text-blue-500"})})};function C(e){let{data:l=[],columns:t,isLoading:a=!1,sorting:r=[],onSortingChange:i,pagination:n,onPaginationChange:o,enablePagination:d=!1}=e,[c]=f.useState("onChange"),[m,u]=f.useState({}),[h,x]=f.useState({}),v=(0,p.b7)({data:l,columns:t,state:{sorting:r,columnSizing:m,columnVisibility:h,...d&&n?{pagination:n}:{}},columnResizeMode:c,onSortingChange:i,onColumnSizingChange:u,onColumnVisibilityChange:x,...d&&o?{onPaginationChange:o}:{},getCoreRowModel:(0,g.sC)(),...d?{getPaginationRowModel:(0,g.G_)()}:{},enableSorting:!0,enableColumnResizing:!0,manualSorting:!0,defaultColumn:{minSize:40,maxSize:500}});return(0,s.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,s.jsx)("div",{className:"overflow-x-auto",children:(0,s.jsx)("div",{className:"relative min-w-full",children:(0,s.jsxs)(j.iA,{className:"[&_td]:py-2 [&_th]:py-2",style:{width:v.getTotalSize(),minWidth:"100%",tableLayout:"fixed"},children:[(0,s.jsx)(j.ss,{children:v.getHeaderGroups().map(e=>(0,s.jsx)(j.SC,{children:e.headers.map(e=>{var l;return(0,s.jsxs)(j.xs,{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)] w-[120px] ml-8":""," ").concat((null===(l=e.column.columnDef.meta)||void 0===l?void 0:l.className)||""),style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},children:[(0,s.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,s.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,p.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&e.column.getCanSort()&&i&&(0,s.jsx)(Z,{sortState:!1!==e.column.getIsSorted()&&e.column.getIsSorted(),onSortChange:l=>{!1===l?i([]):i([{id:e.column.id,desc:"desc"===l}])},columnId:e.column.id})]}),e.column.getCanResize()&&(0,s.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,s.jsx)(j.RM,{children:a?(0,s.jsx)(j.SC,{children:(0,s.jsx)(j.pj,{colSpan:t.length,className:"h-8 text-center",children:(0,s.jsx)("div",{className:"text-center text-gray-500",children:(0,s.jsx)("p",{children:"\uD83D\uDE85 Loading models..."})})})}):v.getRowModel().rows.length>0?v.getRowModel().rows.map(e=>(0,s.jsx)(j.SC,{children:e.getVisibleCells().map(e=>{var l;return(0,s.jsx)(j.pj,{className:"py-0.5 overflow-hidden ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""," ").concat((null===(l=e.column.columnDef.meta)||void 0===l?void 0:l.className)||""),style:{width:"actions"===e.column.id?120:e.column.getSize(),position:"actions"===e.column.id?"sticky":"relative",right:"actions"===e.column.id?0:"auto"},children:(0,p.ie)(e.column.columnDef.cell,e.getContext())},e.id)})},e.id)):(0,s.jsx)(j.SC,{children:(0,s.jsx)(j.pj,{colSpan:t.length,className:"h-8 text-center",children:(0,s.jsx)("div",{className:"text-center text-gray-500",children:(0,s.jsx)("p",{children:"No models found"})})})})})]})})})})}var k=t(45589),S=t(74998),P=t(41649),A=t(78489),E=t(47323),M=t(57840),L=t(99981),F=t(55590),I=t(10868),T=t(79326),R=t(45188);let{Text:z}=M.default,O=(e,l,t,a,r,i,n,o,d,c)=>[{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Model ID"}),accessorKey:"model_info.id",enableSorting:!1,size:130,minSize:80,cell:e=>{let{row:l}=e,t=l.original;return(0,s.jsx)(L.Z,{title:t.model_info.id,children:(0,s.jsx)(z,{ellipsis:!0,className:"text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs cursor-pointer w-full block",style:{fontSize:14,padding:"1px 8px"},onClick:()=>a(t.model_info.id),children:t.model_info.id})})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Model Information"}),accessorKey:"model_name",size:250,minSize:120,cell:e=>{let{row:l}=e,t=l.original,a=i(l.original)||"-",r=(0,s.jsxs)(F.Z,{direction:"vertical",size:12,style:{minWidth:220},children:[(0,s.jsxs)(I.Z,{align:"center",gap:8,children:[(0,s.jsx)(R.K,{provider:t.provider}),(0,s.jsx)(z,{type:"secondary",style:{fontSize:12},ellipsis:!0,children:t.provider||"Unknown provider"})]}),(0,s.jsxs)(F.Z,{direction:"vertical",size:6,children:[(0,s.jsxs)(F.Z,{direction:"vertical",size:2,style:{width:"100%"},children:[(0,s.jsx)(z,{type:"secondary",style:{fontSize:11},children:"Public Model Name"}),(0,s.jsx)(z,{strong:!0,style:{fontSize:13,maxWidth:480},ellipsis:!0,title:a,children:a})]}),(0,s.jsxs)(F.Z,{direction:"vertical",size:2,children:[(0,s.jsx)(z,{type:"secondary",style:{fontSize:11},children:"LiteLLM Model Name"}),(0,s.jsx)(z,{style:{fontSize:13},copyable:{text:t.litellm_model_name||"-"},ellipsis:!0,title:t.litellm_model_name||"-",children:t.litellm_model_name||"-"})]})]})]});return(0,s.jsx)(T.Z,{content:r,placement:"right",arrow:{pointAtCenter:!0},styles:{root:{maxWidth:500}},children:(0,s.jsxs)("div",{className:"flex items-start space-x-2 min-w-0 w-full cursor-pointer",children:[(0,s.jsx)("div",{className:"flex-shrink-0 mt-0.5",children:t.provider?(0,s.jsx)(R.K,{provider:t.provider}):(0,s.jsx)("div",{className:"w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",children:"-"})}),(0,s.jsxs)("div",{className:"flex flex-col min-w-0 flex-1",children:[(0,s.jsx)(z,{ellipsis:!0,className:"text-gray-900",style:{fontSize:12,fontWeight:500,lineHeight:"16px"},children:a}),(0,s.jsx)(z,{ellipsis:!0,type:"secondary",style:{fontSize:12,lineHeight:"16px",marginTop:2},children:t.litellm_model_name||"-"})]})]})})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Credentials"}),accessorKey:"litellm_credential_name",enableSorting:!1,size:180,minSize:100,cell:e=>{var l;let{row:t}=e,a=null===(l=t.original.litellm_params)||void 0===l?void 0:l.litellm_credential_name;return a?(0,s.jsx)(L.Z,{title:"Credential: ".concat(a),children:(0,s.jsxs)("div",{className:"flex items-center space-x-2 min-w-0 w-full",children:[(0,s.jsx)(k.Z,{className:"w-4 h-4 text-blue-500 flex-shrink-0"}),(0,s.jsx)("span",{className:"text-xs truncate",title:a,children:a})]})}):(0,s.jsxs)("div",{className:"flex items-center space-x-2 min-w-0 w-full",children:[(0,s.jsx)(k.Z,{className:"w-4 h-4 text-gray-300 flex-shrink-0"}),(0,s.jsx)("span",{className:"text-xs text-gray-400",children:"No credentials"})]})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Created By"}),accessorKey:"model_info.created_by",sortingFn:"datetime",size:160,minSize:100,cell:e=>{var l;let{row:t}=e,a=t.original,r=!(null===(l=a.model_info)||void 0===l?void 0:l.db_model),i=a.model_info.created_by,n=a.model_info.created_at?new Date(a.model_info.created_at).toLocaleDateString():null;return(0,s.jsxs)("div",{className:"flex flex-col min-w-0 w-full",children:[(0,s.jsx)("div",{className:"text-xs font-medium text-gray-900 truncate",title:r?"Defined in config":i||"Unknown",children:r?"Defined in config":i||"Unknown"}),(0,s.jsx)("div",{className:"text-xs text-gray-500 truncate mt-0.5",title:r?"Config file":n||"Unknown date",children:r?"-":n||"Unknown date"})]})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Updated At"}),accessorKey:"model_info.updated_at",sortingFn:"datetime",size:120,minSize:80,cell:e=>{let{row:l}=e,t=l.original;return(0,s.jsx)("span",{className:"text-xs",children:t.model_info.updated_at?new Date(t.model_info.updated_at).toLocaleDateString():"-"})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Costs"}),accessorKey:"input_cost",size:120,minSize:80,cell:e=>{let{row:l}=e,t=l.original,a=t.input_cost,r=t.output_cost;return a||r?(0,s.jsx)(L.Z,{title:"Cost per 1M tokens",children:(0,s.jsxs)("div",{className:"flex flex-col min-w-0 w-full",children:[a&&(0,s.jsxs)("div",{className:"text-xs font-medium text-gray-900 truncate",children:["In: $",a]}),r&&(0,s.jsxs)("div",{className:"text-xs text-gray-500 truncate mt-0.5",children:["Out: $",r]})]})}):(0,s.jsx)("div",{className:"w-full",children:(0,s.jsx)("span",{className:"text-xs text-gray-400",children:"-"})})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Team ID"}),accessorKey:"model_info.team_id",enableSorting:!1,size:130,minSize:80,cell:e=>{let{row:l}=e,t=l.original;return t.model_info.team_id?(0,s.jsx)("div",{className:"overflow-hidden w-full",children:(0,s.jsx)(L.Z,{title:t.model_info.team_id,children:(0,s.jsxs)(A.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 w-full",onClick:()=>r(t.model_info.team_id),children:[t.model_info.team_id.slice(0,7),"..."]})})}):"-"}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Model Access Group"}),accessorKey:"model_info.model_access_group",enableSorting:!1,size:180,minSize:100,cell:e=>{let{row:l}=e,t=l.original,a=t.model_info.access_groups;if(!a||0===a.length)return"-";let r=t.model_info.id,i=d.has(r),n=a.length>1,o=()=>{let e=new Set(d);i?e.delete(r):e.add(r),c(e)};return(0,s.jsxs)("div",{className:"flex items-center gap-1 overflow-hidden w-full",children:[(0,s.jsx)(P.Z,{size:"xs",color:"blue",className:"text-xs px-1.5 py-0.5 h-5 leading-tight flex-shrink-0",children:a[0]}),(i||!n&&2===a.length)&&a.slice(1).map((e,l)=>(0,s.jsx)(P.Z,{size:"xs",color:"blue",className:"text-xs px-1.5 py-0.5 h-5 leading-tight flex-shrink-0",children:e},l+1)),n&&(0,s.jsx)("button",{onClick:e=>{e.stopPropagation(),o()},className:"text-xs text-blue-600 hover:text-blue-800 px-1 py-0.5 rounded hover:bg-blue-50 h-5 leading-tight flex-shrink-0 whitespace-nowrap",children:i?"−":"+".concat(a.length-1)})]})}},{header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Status"}),accessorKey:"model_info.db_model",size:120,minSize:80,cell:e=>{let{row:l}=e,t=l.original;return(0,s.jsx)("div",{className:"\n inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium\n ".concat(t.model_info.db_model?"bg-blue-50 text-blue-600":"bg-gray-100 text-gray-600","\n "),children:t.model_info.db_model?"DB Model":"Config Model"})}},{id:"actions",header:()=>(0,s.jsx)("span",{className:"text-sm font-semibold",children:"Actions"}),size:60,minSize:40,enableResizing:!1,cell:t=>{var r,i;let{row:n}=t,o=n.original,d="Admin"===e||(null===(r=o.model_info)||void 0===r?void 0:r.created_by)===l,c=!(null===(i=o.model_info)||void 0===i?void 0:i.db_model);return(0,s.jsx)("div",{className:"flex items-center justify-end gap-2 pr-4",children:c?(0,s.jsx)(L.Z,{title:"Config model cannot be deleted on the dashboard. Please delete it from the config file.",children:(0,s.jsx)(E.Z,{icon:S.Z,size:"sm",className:"opacity-50 cursor-not-allowed"})}):(0,s.jsx)(L.Z,{title:"Delete model",children:(0,s.jsx)(E.Z,{icon:S.Z,size:"sm",onClick:()=>{d&&a(o.model_info.id)},className:d?"cursor-pointer hover:text-red-600":"opacity-50 cursor-not-allowed"})})})}}],V=e=>{var l;return(null==e?void 0:null===(l=e.model_info)||void 0===l?void 0:l.team_public_model_name)?e.model_info.team_public_model_name:(null==e?void 0:e.model_name)||"-"};var q=t(15424),D=t(67101),B=t(27281),G=t(57365),U=t(29706),H=t(84264),K=t(50337),J=t(10353),W=t(7310),Y=t.n(W);let $=(e,l)=>{if(!(null==e?void 0:e.data))return{data:[]};let t=JSON.parse(JSON.stringify(e.data));for(let e=0;e{let[l]=e;return"model"!==l&&"api_base"!==l}))),t[e].provider=c,t[e].input_cost=m,t[e].output_cost=u,t[e].litellm_model_name=n,t[e].input_cost&&(t[e].input_cost=(1e6*Number(t[e].input_cost)).toFixed(2)),t[e].output_cost&&(t[e].output_cost=(1e6*Number(t[e].output_cost)).toFixed(2)),t[e].max_tokens=h,t[e].max_input_tokens=x,t[e].api_base=null==i?void 0:null===(r=i.litellm_params)||void 0===r?void 0:r.api_base,t[e].cleanedLitellmParams=p}return{data:t}};var X=e=>{let{selectedModelGroup:l,setSelectedModelGroup:t,availableModelGroups:a,availableModelAccessGroups:r,setSelectedModelId:i,setSelectedTeamId:o}=e,{data:d,isLoading:c}=m(),{userId:h,userRole:p,premiumUser:g}=(0,n.Z)(),{data:j,isLoading:v}=(0,x.y2)(),[_,y]=(0,f.useState)(""),[b,N]=(0,f.useState)(""),[w,Z]=(0,f.useState)("current_team"),[k,S]=(0,f.useState)("personal"),[P,A]=(0,f.useState)(!1),[E,M]=(0,f.useState)(null),[L,F]=(0,f.useState)(new Set),[I,T]=(0,f.useState)(1),[R]=(0,f.useState)(50),[z,W]=(0,f.useState)({pageIndex:0,pageSize:50}),[X,Q]=(0,f.useState)([]),ee=(0,f.useMemo)(()=>Y()(e=>{N(e),T(1),W(e=>({...e,pageIndex:0}))},200),[]);(0,f.useEffect)(()=>(ee(_),()=>{ee.cancel()}),[_,ee]);let el="personal"===k?void 0:k.team_id,et=(0,f.useMemo)(()=>{if(0===X.length)return;let e=X[0];return({input_cost:"costs",model_info_db_model:"status",model_info_created_by:"created_at",model_info_updated_at:"updated_at"})[e.id]||e.id},[X]),es=(0,f.useMemo)(()=>{if(0!==X.length)return X[0].desc?"desc":"asc"},[X]),{data:ea,isLoading:er}=(0,u.XP)(I,R,b||void 0,void 0,el,et,es),ei=er||c,en=e=>null!=d&&"object"==typeof d&&e in d?d[e].litellm_provider:"openai",eo=(0,f.useMemo)(()=>ea?$(ea,en):{data:[]},[ea,d]),ed=(0,f.useMemo)(()=>{var e,l,t,s;return ea?{total_count:null!==(e=ea.total_count)&&void 0!==e?e:0,current_page:null!==(l=ea.current_page)&&void 0!==l?l:1,total_pages:null!==(t=ea.total_pages)&&void 0!==t?t:1,size:null!==(s=ea.size)&&void 0!==s?s:R}:{total_count:0,current_page:1,total_pages:1,size:R}},[ea,R]),ec=(0,f.useMemo)(()=>eo&&eo.data&&0!==eo.data.length?eo.data.filter(e=>{var t,s;let a="all"===l||e.model_name===l||!l||"wildcard"===l&&(null===(t=e.model_name)||void 0===t?void 0:t.includes("*")),r="all"===E||(null===(s=e.model_info.access_groups)||void 0===s?void 0:s.includes(E))||!E;return a&&r}):[],[eo,l,E]);return(0,f.useEffect)(()=>{W(e=>({...e,pageIndex:0})),T(1)},[l,E]),(0,f.useEffect)(()=>{T(1),W(e=>({...e,pageIndex:0}))},[el]),(0,f.useEffect)(()=>{T(1),W(e=>({...e,pageIndex:0}))},[X]),(0,s.jsx)(U.Z,{children:(0,s.jsx)(D.Z,{children:(0,s.jsx)("div",{className:"flex flex-col space-y-4",children:(0,s.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,s.jsxs)("div",{className:"border-b px-6 py-4 bg-gray-50",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsxs)("div",{className:"flex items-center gap-4",children:[(0,s.jsx)(H.Z,{className:"text-lg font-semibold text-gray-900",children:"Current Team:"}),ei?(0,s.jsx)(K.Z.Input,{active:!0,style:{width:320,height:36}}):(0,s.jsxs)(B.Z,{className:"w-80",defaultValue:"personal",value:"personal"===k?"personal":k.team_id,onValueChange:e=>{if("personal"===e)S("personal"),T(1),W(e=>({...e,pageIndex:0}));else{let l=null==j?void 0:j.find(l=>l.team_id===e);l&&(S(l),T(1),W(e=>({...e,pageIndex:0})))}},children:[(0,s.jsx)(G.Z,{value:"personal",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full"}),(0,s.jsx)("span",{className:"font-medium",children:"Personal"})]})}),v?(0,s.jsx)(G.Z,{value:"loading",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(J.Z,{size:"small"}),(0,s.jsx)("span",{className:"font-medium text-gray-500",children:"Loading teams..."})]})}):null==j?void 0:j.filter(e=>e.team_id).map(e=>(0,s.jsx)(G.Z,{value:e.team_id,children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,s.jsx)("span",{className:"font-medium",children:e.team_alias?"".concat(e.team_alias.slice(0,30),"..."):"Team ".concat(e.team_id.slice(0,30),"...")})]})},e.team_id))]})]}),(0,s.jsxs)("div",{className:"flex items-center gap-4",children:[(0,s.jsx)(H.Z,{className:"text-lg font-semibold text-gray-900",children:"View:"}),ei?(0,s.jsx)(K.Z.Input,{active:!0,style:{width:256,height:36}}):(0,s.jsxs)(B.Z,{className:"w-64",defaultValue:"current_team",value:w,onValueChange:e=>Z(e),children:[(0,s.jsx)(G.Z,{value:"current_team",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-purple-500 rounded-full"}),(0,s.jsx)("span",{className:"font-medium",children:"Current Team Models"})]})}),(0,s.jsx)(G.Z,{value:"all",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-gray-500 rounded-full"}),(0,s.jsx)("span",{className:"font-medium",children:"All Available Models"})]})})]})]})]}),"current_team"===w&&(0,s.jsxs)("div",{className:"flex items-start gap-2 mt-3",children:[(0,s.jsx)(q.Z,{className:"text-gray-400 mt-0.5 flex-shrink-0 text-xs"}),(0,s.jsx)("div",{className:"text-xs text-gray-500",children:"personal"===k?(0,s.jsxs)("span",{children:["To access these models: Create a Virtual Key without selecting a team on the"," ",(0,s.jsx)("a",{href:"/public?login=success&page=api-keys",className:"text-gray-600 hover:text-gray-800 underline",children:"Virtual Keys page"})]}):(0,s.jsxs)("span",{children:['To access these models: Create a Virtual Key and select Team as "',"string"!=typeof k?k.team_alias||k.team_id:"",'" on the'," ",(0,s.jsx)("a",{href:"/public?login=success&page=api-keys",className:"text-gray-600 hover:text-gray-800 underline",children:"Virtual Keys page"})]})})]})]}),(0,s.jsx)("div",{className:"border-b px-6 py-4",children:(0,s.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,s.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,s.jsxs)("div",{className:"relative w-64",children:[(0,s.jsx)("input",{type:"text",placeholder:"Search model names...",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:_,onChange:e=>y(e.target.value)}),(0,s.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,s.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,s.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ".concat(P?"bg-gray-100":""),onClick:()=>A(!P),children:[(0,s.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,s.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"]}),(0,s.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>{y(""),t("all"),M(null),S("personal"),Z("current_team"),T(1),W({pageIndex:0,pageSize:50}),Q([])},children:[(0,s.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,s.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"]})]}),P&&(0,s.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,s.jsx)("div",{className:"w-64",children:(0,s.jsxs)(B.Z,{value:null!=l?l:"all",onValueChange:e=>t("all"===e?"all":e),placeholder:"Filter by Public Model Name",children:[(0,s.jsx)(G.Z,{value:"all",children:"All Models"}),(0,s.jsx)(G.Z,{value:"wildcard",children:"Wildcard Models (*)"}),a.map((e,l)=>(0,s.jsx)(G.Z,{value:e,children:e},l))]})}),(0,s.jsx)("div",{className:"w-64",children:(0,s.jsxs)(B.Z,{value:null!=E?E:"all",onValueChange:e=>M("all"===e?null:e),placeholder:"Filter by Model Access Group",children:[(0,s.jsx)(G.Z,{value:"all",children:"All Model Access Groups"}),r.map((e,l)=>(0,s.jsx)(G.Z,{value:e,children:e},l))]})})]}),(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[ei?(0,s.jsx)(K.Z.Input,{active:!0,style:{width:184,height:20}}):(0,s.jsx)("span",{className:"text-sm text-gray-700",children:ed.total_count>0?"Showing ".concat((I-1)*R+1," - ").concat(Math.min(I*R,ed.total_count)," of ").concat(ed.total_count," results"):"Showing 0 results"}),(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[ei?(0,s.jsx)(K.Z.Button,{active:!0,style:{width:84,height:30}}):(0,s.jsx)("button",{onClick:()=>{T(I-1),W(e=>({...e,pageIndex:0}))},disabled:1===I,className:"px-3 py-1 text-sm border rounded-md ".concat(1===I?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Previous"}),ei?(0,s.jsx)(K.Z.Button,{active:!0,style:{width:56,height:30}}):(0,s.jsx)("button",{onClick:()=>{T(I+1),W(e=>({...e,pageIndex:0}))},disabled:I>=ed.total_pages,className:"px-3 py-1 text-sm border rounded-md ".concat(I>=ed.total_pages?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Next"})]})]})]})}),(0,s.jsx)(C,{columns:O(p,h,g,i,o,V,()=>{},()=>{},L,F),data:ec,isLoading:er,sorting:X,onSortingChange:Q,pagination:z,onPaginationChange:W,enablePagination:!0})]})})})})},Q=t(96761),ee=t(12221);let el={"BadRequestError (400)":"BadRequestErrorRetries","AuthenticationError (401)":"AuthenticationErrorRetries","TimeoutError (408)":"TimeoutErrorRetries","RateLimitError (429)":"RateLimitErrorRetries","ContentPolicyViolationError (400)":"ContentPolicyViolationErrorRetries","InternalServerError (500)":"InternalServerErrorRetries"};var et=e=>{let{selectedModelGroup:l,setSelectedModelGroup:t,availableModelGroups:a,globalRetryPolicy:r,setGlobalRetryPolicy:i,defaultRetry:n,modelGroupRetryPolicy:o,setModelGroupRetryPolicy:d,handleSaveRetrySettings:c}=e;return(0,s.jsxs)(U.Z,{children:[(0,s.jsx)("div",{className:"flex items-center gap-4 mb-6",children:(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(H.Z,{children:"Retry Policy Scope:"}),(0,s.jsxs)(B.Z,{className:"ml-2 w-48",defaultValue:"global",value:"global"===l?"global":l||a[0],onValueChange:e=>t(e),children:[(0,s.jsx)(G.Z,{value:"global",children:"Global Default"}),a.map((e,l)=>(0,s.jsx)(G.Z,{value:e,onClick:()=>t(e),children:e},l))]})]})}),"global"===l?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(Q.Z,{children:"Global Retry Policy"}),(0,s.jsx)(H.Z,{className:"mb-6",children:"Default retry settings applied to all model groups unless overridden"})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)(Q.Z,{children:["Retry Policy for ",l]}),(0,s.jsx)(H.Z,{className:"mb-6",children:"Model-specific retry settings. Falls back to global defaults if not set."})]}),el&&(0,s.jsx)("table",{children:(0,s.jsx)("tbody",{children:Object.entries(el).map((e,t)=>{var a,c,m,u;let h,[x,p]=e;if("global"===l)h=null!==(a=null==r?void 0:r[p])&&void 0!==a?a:n;else{let e=null==o?void 0:null===(c=o[l])||void 0===c?void 0:c[p];h=null!=e?e:null!==(m=null==r?void 0:r[p])&&void 0!==m?m:n}return(0,s.jsxs)("tr",{className:"flex justify-between items-center mt-2",children:[(0,s.jsxs)("td",{children:[(0,s.jsx)(H.Z,{children:x}),"global"!==l&&(0,s.jsxs)(H.Z,{className:"text-xs text-gray-500 ml-2",children:["(Global: ",null!==(u=null==r?void 0:r[p])&&void 0!==u?u:n,")"]})]}),(0,s.jsx)("td",{children:(0,s.jsx)(ee.Z,{className:"ml-5",value:h,min:0,step:1,onChange:e=>{"global"===l?i(l=>null==e?l:{...null!=l?l:{},[p]:e}):d(t=>{var s;let a=null!==(s=null==t?void 0:t[l])&&void 0!==s?s:{};return{...null!=t?t:{},[l]:{...a,[p]:e}}})}})})]},t)})})}),(0,s.jsx)(A.Z,{className:"mt-6 mr-8",onClick:c,children:"Save"})]})},es=t(867),ea=t(5945),er=t(3810),ei=t(22116),en=t(89245),eo=t(5540),ed=t(8881),ec=t(9114);let{Text:em}=M.default;var eu=e=>{let{accessToken:l,onReloadSuccess:t,buttonText:r="Reload Price Data",showIcon:i=!0,size:n="middle",type:o="primary",className:d=""}=e,[c,m]=(0,f.useState)(!1),[u,h]=(0,f.useState)(!1),[x,p]=(0,f.useState)(!1),[g,j]=(0,f.useState)(!1),[v,y]=(0,f.useState)(6),[b,N]=(0,f.useState)(null),[w,Z]=(0,f.useState)(!1);(0,f.useEffect)(()=>{C();let e=setInterval(()=>{C()},3e4);return()=>clearInterval(e)},[l]);let C=async()=>{if(l){Z(!0);try{console.log("Fetching reload status...");let e=await (0,a.getModelCostMapReloadStatus)(l);console.log("Received status:",e),N(e)}catch(e){console.error("Failed to fetch reload status:",e),N({scheduled:!1,interval_hours:null,last_run:null,next_run:null})}finally{Z(!1)}}},k=async()=>{if(!l){ec.ZP.fromBackend("No access token available");return}m(!0);try{let e=await (0,a.reloadModelCostMap)(l);"success"===e.status?(ec.ZP.success("Price data reloaded successfully! ".concat(e.models_count||0," models updated.")),null==t||t(),await C()):ec.ZP.fromBackend("Failed to reload price data")}catch(e){console.error("Error reloading price data:",e),ec.ZP.fromBackend("Failed to reload price data. Please try again.")}finally{m(!1)}},S=async()=>{if(!l){ec.ZP.fromBackend("No access token available");return}if(v<=0){ec.ZP.fromBackend("Hours must be greater than 0");return}h(!0);try{let e=await (0,a.scheduleModelCostMapReload)(l,v);"success"===e.status?(ec.ZP.success("Periodic reload scheduled for every ".concat(v," hours")),j(!1),await C()):ec.ZP.fromBackend("Failed to schedule periodic reload")}catch(e){console.error("Error scheduling reload:",e),ec.ZP.fromBackend("Failed to schedule periodic reload. Please try again.")}finally{h(!1)}},P=async()=>{if(!l){ec.ZP.fromBackend("No access token available");return}p(!0);try{let e=await (0,a.cancelModelCostMapReload)(l);"success"===e.status?(ec.ZP.success("Periodic reload cancelled successfully"),await C()):ec.ZP.fromBackend("Failed to cancel periodic reload")}catch(e){console.error("Error cancelling reload:",e),ec.ZP.fromBackend("Failed to cancel periodic reload. Please try again.")}finally{p(!1)}},A=e=>{if(!e)return"Never";try{return new Date(e).toLocaleString()}catch(l){return e}};return(0,s.jsxs)("div",{className:d,children:[(0,s.jsxs)(F.Z,{direction:"horizontal",size:"middle",style:{marginBottom:16},children:[(0,s.jsx)(es.Z,{title:"Hard Refresh Price Data",description:"This will immediately fetch the latest pricing information from the remote source. Continue?",onConfirm:k,okText:"Yes",cancelText:"No",okButtonProps:{style:{backgroundColor:"#6366f1",borderColor:"#6366f1",color:"white",fontWeight:"500",borderRadius:"0.375rem",padding:"0.375rem 0.75rem",height:"auto",fontSize:"0.875rem",lineHeight:"1.25rem",transition:"all 0.2s ease-in-out"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#4f46e5"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#6366f1"}},children:(0,s.jsx)(_.ZP,{type:o,size:n,loading:c,icon:i?(0,s.jsx)(en.Z,{}):void 0,style:{backgroundColor:"#6366f1",borderColor:"#6366f1",color:"white",fontWeight:"500",borderRadius:"0.375rem",padding:"0.375rem 0.75rem",height:"auto",fontSize:"0.875rem",lineHeight:"1.25rem",transition:"all 0.2s ease-in-out"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#4f46e5"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#6366f1"},children:r})}),(null==b?void 0:b.scheduled)?(0,s.jsx)(_.ZP,{type:"default",size:n,danger:!0,icon:(0,s.jsx)(ed.Z,{}),loading:x,onClick:P,style:{borderColor:"#ff4d4f",color:"#ff4d4f",fontWeight:"500",borderRadius:"0.375rem",padding:"0.375rem 0.75rem",height:"auto",fontSize:"0.875rem",lineHeight:"1.25rem"},children:"Cancel Periodic Reload"}):(0,s.jsx)(_.ZP,{type:"default",size:n,icon:(0,s.jsx)(eo.Z,{}),onClick:()=>j(!0),style:{borderColor:"#d9d9d9",color:"#6366f1",fontWeight:"500",borderRadius:"0.375rem",padding:"0.375rem 0.75rem",height:"auto",fontSize:"0.875rem",lineHeight:"1.25rem"},children:"Set Up Periodic Reload"})]}),b&&(0,s.jsx)(ea.Z,{size:"small",style:{backgroundColor:"#f8f9fa",border:"1px solid #e9ecef",borderRadius:8},children:(0,s.jsxs)(F.Z,{direction:"vertical",size:"small",style:{width:"100%"},children:[b.scheduled?(0,s.jsx)("div",{children:(0,s.jsxs)(er.Z,{color:"green",icon:(0,s.jsx)(eo.Z,{}),children:["Scheduled every ",b.interval_hours," hours"]})}):(0,s.jsx)(em,{type:"secondary",children:"No periodic reload scheduled"}),(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsx)(em,{type:"secondary",style:{fontSize:"12px"},children:"Last run:"}),(0,s.jsx)(em,{style:{fontSize:"12px"},children:A(b.last_run)})]}),b.scheduled&&(0,s.jsxs)(s.Fragment,{children:[b.next_run&&(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsx)(em,{type:"secondary",style:{fontSize:"12px"},children:"Next run:"}),(0,s.jsx)(em,{style:{fontSize:"12px"},children:A(b.next_run)})]}),(0,s.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,s.jsx)(em,{type:"secondary",style:{fontSize:"12px"},children:"Status:"}),(0,s.jsx)(er.Z,{color:(null==b?void 0:b.scheduled)?b.last_run?"success":"processing":"default",children:(null==b?void 0:b.scheduled)?b.last_run?"Active":"Ready":"Not scheduled"})]})]})]})}),(0,s.jsxs)(ei.Z,{title:"Set Up Periodic Reload",open:g,onOk:S,onCancel:()=>j(!1),confirmLoading:u,okText:"Schedule",cancelText:"Cancel",okButtonProps:{style:{backgroundColor:"#6366f1",borderColor:"#6366f1",color:"white"}},children:[(0,s.jsx)("div",{style:{marginBottom:16},children:(0,s.jsx)(em,{children:"Set up automatic reload of price data every:"})}),(0,s.jsx)("div",{style:{marginBottom:16},children:(0,s.jsx)(ee.Z,{min:1,max:168,value:v,onChange:e=>y(e||6),addonAfter:"hours",style:{width:"100%"}})}),(0,s.jsx)("div",{children:(0,s.jsxs)(em,{type:"secondary",children:["This will automatically fetch the latest pricing data from the remote source every ",v," hours."]})})]})]})},eh=()=>{let{accessToken:e}=(0,n.Z)(),{refetch:l}=m();return(0,s.jsx)(U.Z,{children:(0,s.jsxs)("div",{className:"p-6",children:[(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsx)(Q.Z,{children:"Price Data Management"}),(0,s.jsx)(H.Z,{className:"text-tremor-content",children:"Manage model pricing data and configure automatic reload schedules"})]}),(0,s.jsx)(eu,{accessToken:e,onReloadSuccess:()=>{l()},buttonText:"Reload Price Data",size:"middle",type:"primary",className:"w-full"})]})})},ex=t(42673);let ep=async(e,l,t)=>{try{var s,a;console.log("handling submit for formValues:",e);let l=e.model_mappings||[];if("model_mappings"in e&&delete e.model_mappings,e.model&&e.model.includes("all-wildcard")){let t=e.custom_llm_provider,a=(null!==(s=ex.fK[t])&&void 0!==s?s:t.toLowerCase())+"/*";e.model_name=a,l.push({public_name:a,litellm_model:a}),e.model=a}let t=[];for(let s of l){let l={},r={},i=s.public_name;for(let[t,i]of(l.model=s.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),l.model=s.litellm_model,console.log("formValues add deployment:",e),Object.entries(e)))if(""!==i&&"custom_pricing"!==t&&"pricing_model"!==t&&"cache_control"!==t){if("model_name"==t)l.model=i;else if("custom_llm_provider"==t){console.log("custom_llm_provider:",i);let e=null!==(a=ex.fK[i])&&void 0!==a?a:i.toLowerCase();l.custom_llm_provider=e,console.log("custom_llm_provider mappingResult:",e)}else if("model"==t)continue;else if("base_model"===t)r[t]=i;else if("team_id"===t)r.team_id=i;else if("model_access_group"===t)r.access_groups=i;else if("mode"==t)console.log("placing mode in modelInfo"),r.mode=i,delete l.mode;else if("custom_model_name"===t)l.model=i;else if("litellm_extra_params"==t){console.log("litellm_extra_params:",i);let e={};if(i&&void 0!=i){try{e=JSON.parse(i)}catch(e){throw ec.ZP.fromBackend("Failed to parse LiteLLM Extra Params: "+e),Error("Failed to parse litellm_extra_params: "+e)}for(let[t,s]of Object.entries(e))l[t]=s}}else if("model_info_params"==t){console.log("model_info_params:",i);let e={};if(i&&void 0!=i){try{e=JSON.parse(i)}catch(e){throw ec.ZP.fromBackend("Failed to parse LiteLLM Extra Params: "+e),Error("Failed to parse litellm_extra_params: "+e)}for(let[l,t]of Object.entries(e))r[l]=t}}else if("input_cost_per_token"===t||"output_cost_per_token"===t||"input_cost_per_second"===t){i&&(l[t]=Number(i));continue}else l[t]=i}t.push({litellmParamsObj:l,modelInfoObj:r,modelName:i})}return t}catch(e){ec.ZP.fromBackend("Failed to create model: "+e)}},eg=async(e,l,t,s)=>{try{let r=await ep(e,l,t);if(!r||0===r.length)return;for(let e of r){let{litellmParamsObj:t,modelInfoObj:s,modelName:r}=e,i={model_name:r,litellm_params:t,model_info:s},n=await (0,a.modelCreateCall)(l,i);console.log("response for model create call: ".concat(n.data))}s&&s(),t.resetFields()}catch(e){ec.ZP.fromBackend("Failed to add model: "+e)}};var ef=t(53410),ej=t(62490),ev=t(10032),e_=t(21609),ey=t(31283),eb=t(37592);let eN=(0,i.n)("providerFields"),ew=()=>(0,r.a)({queryKey:eN.list({}),queryFn:async()=>await (0,a.getProviderCreateMetadata)(),staleTime:864e5,gcTime:864e5});var eZ=t(3632),eC=t(56522),ek=t(47451),eS=t(69410),eP=t(65319),eA=t(4260);let{Link:eE}=M.default,eM=e=>{var l,t,s,a,r;let i="password"===e.field_type?"password":"select"===e.field_type?"select":"upload"===e.field_type?"upload":"textarea"===e.field_type?"textarea":"text";return{key:e.key,label:e.label,placeholder:null!==(l=e.placeholder)&&void 0!==l?l:void 0,tooltip:null!==(t=e.tooltip)&&void 0!==t?t:void 0,required:null!==(s=e.required)&&void 0!==s&&s,type:i,options:null!==(a=e.options)&&void 0!==a?a:void 0,defaultValue:null!==(r=e.default_value)&&void 0!==r?r:void 0}},eL={};var eF=e=>{let{selectedProvider:l,uploadProps:t}=e,a=ex.Cl[l],r=ev.Z.useFormInstance(),{data:i,isLoading:n,error:o}=ew(),d=f.useMemo(()=>{if(!i)return null;let e={};return i.forEach(l=>{let t=l.provider_display_name,s=l.credential_fields.map(eM);e[t]=s,l.provider&&(e[l.provider]=s),l.litellm_provider&&(e[l.litellm_provider]=s)}),e},[i]);f.useEffect(()=>{d&&Object.assign(eL,d)},[d]);let c=f.useMemo(()=>{var e;let t=null!==(e=eL[a])&&void 0!==e?e:eL[l];if(t)return t;if(!i)return[];let s=i.find(e=>e.provider_display_name===a||e.provider===l||e.litellm_provider===l);if(!s)return[];let r=s.credential_fields.map(eM);return eL[s.provider_display_name]=r,s.provider&&(eL[s.provider]=r),s.litellm_provider&&(eL[s.litellm_provider]=r),r},[a,l,i]),m={name:"file",accept:".json",beforeUpload:e=>{if("application/json"===e.type){let l=new FileReader;l.onload=e=>{if(e.target){let l=e.target.result;console.log("Setting field value from JSON, length: ".concat(l.length)),r.setFieldsValue({vertex_credentials:l}),console.log("Form values after setting:",r.getFieldsValue())}},l.readAsText(e)}return!1},onChange(e){console.log("Upload onChange triggered in ProviderSpecificFields"),console.log("Current form values:",r.getFieldsValue()),"uploading"!==e.file.status&&console.log(e.file,e.fileList)}};return(0,s.jsxs)(s.Fragment,{children:[n&&0===c.length&&(0,s.jsx)(ek.Z,{children:(0,s.jsx)(eS.Z,{span:24,children:(0,s.jsx)(eC.x,{className:"mb-2",children:"Loading provider fields..."})})}),o&&0===c.length&&(0,s.jsx)(ek.Z,{children:(0,s.jsx)(eS.Z,{span:24,children:(0,s.jsx)(eC.x,{className:"mb-2 text-red-500",children:o instanceof Error?o.message:"Failed to load provider credential fields"})})}),c.map(e=>{var l;return(0,s.jsxs)(f.Fragment,{children:[(0,s.jsx)(ev.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,s.jsx)(eb.default,{placeholder:e.placeholder,defaultValue:e.defaultValue,children:null===(l=e.options)||void 0===l?void 0:l.map(e=>(0,s.jsx)(eb.default.Option,{value:e,children:e},e))}):"upload"===e.type?(0,s.jsx)(eP.default,{...m,onChange:l=>{(null==t?void 0:t.onChange)&&t.onChange(l),setTimeout(()=>{let l=r.getFieldValue(e.key);console.log("".concat(e.key," value after upload:"),JSON.stringify(l))},500)},children:(0,s.jsx)(_.ZP,{icon:(0,s.jsx)(eZ.Z,{}),children:"Click to Upload"})}):"textarea"===e.type?(0,s.jsx)(eA.default.TextArea,{placeholder:e.placeholder,defaultValue:e.defaultValue,rows:6,style:{fontFamily:"monospace",fontSize:"12px"}}):(0,s.jsx)(eC.o,{placeholder:e.placeholder,type:"password"===e.type?"password":"text",defaultValue:e.defaultValue})}),"vertex_credentials"===e.key&&(0,s.jsx)(ek.Z,{children:(0,s.jsx)(eS.Z,{children:(0,s.jsx)(eC.x,{className:"mb-3 mt-1",children:"Give a gcp service account(.json file)"})})}),"base_model"===e.key&&(0,s.jsxs)(ek.Z,{children:[(0,s.jsx)(eS.Z,{span:10}),(0,s.jsx)(eS.Z,{span:10,children:(0,s.jsxs)(eC.x,{className:"mb-2",children:["The actual model your azure deployment uses. Used for accurate cost tracking. Select name from"," ",(0,s.jsx)(eE,{href:"https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json",target:"_blank",children:"here"})]})})]})]},e.key)})]})};let{Link:eI}=M.default;var eT=e=>{let{open:l,onCancel:t,onAddCredential:a,uploadProps:r}=e,[i]=ev.Z.useForm(),[n,o]=(0,f.useState)(ex.Cl.OpenAI);return(0,s.jsx)(ei.Z,{title:"Add New Credential",open:l,onCancel:()=>{t(),i.resetFields()},footer:null,width:600,children:(0,s.jsxs)(ev.Z,{form:i,onFinish:e=>{a(Object.entries(e).reduce((e,l)=>{let[t,s]=l;return""!==s&&null!=s&&(e[t]=s),e},{})),i.resetFields()},layout:"vertical",children:[(0,s.jsx)(ev.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],children:(0,s.jsx)(ey.o,{placeholder:"Enter a friendly name for these credentials"})}),(0,s.jsx)(ev.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,s.jsx)(eb.default,{showSearch:!0,onChange:e=>{o(e),i.setFieldValue("custom_llm_provider",e)},children:Object.entries(ex.Cl).map(e=>{let[l,t]=e;return(0,s.jsx)(eb.default.Option,{value:l,children:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("img",{src:ex.cd[t],alt:"".concat(l," logo"),className:"w-5 h-5",onError:e=>{let l=e.target,s=l.parentElement;if(s){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=t.charAt(0),s.replaceChild(e,l)}}}),(0,s.jsx)("span",{children:t})]})},l)})})}),(0,s.jsx)(eF,{selectedProvider:n,uploadProps:r}),(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(L.Z,{title:"Get help on our github",children:(0,s.jsx)(eI,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(_.ZP,{onClick:()=>{t(),i.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,s.jsx)(_.ZP,{htmlType:"submit",children:"Add Credential"})]})]})]})})};let{Link:eR}=M.default;function ez(e){let{open:l,onCancel:t,onUpdateCredential:a,uploadProps:r,existingCredential:i}=e,[n]=ev.Z.useForm(),[o,d]=(0,f.useState)(ex.Cl.Anthropic);return(0,f.useEffect)(()=>{if(i){let e=Object.entries(i.credential_values||{}).reduce((e,l)=>{let[t,s]=l;return e[t]=null!=s?s:null,e},{});n.setFieldsValue({credential_name:i.credential_name,custom_llm_provider:i.credential_info.custom_llm_provider,...e}),d(i.credential_info.custom_llm_provider)}},[i]),(0,s.jsx)(ei.Z,{title:"Edit Credential",open:l,onCancel:()=>{t(),n.resetFields()},footer:null,width:600,destroyOnHidden:!0,children:(0,s.jsxs)(ev.Z,{form:n,onFinish:e=>{a(Object.entries(e).reduce((e,l)=>{let[t,s]=l;return""!==s&&null!=s&&(e[t]=s),e},{})),n.resetFields()},layout:"vertical",children:[(0,s.jsx)(ev.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==i?void 0:i.credential_name,children:(0,s.jsx)(ey.o,{placeholder:"Enter a friendly name for these credentials",disabled:null!=i&&!!i.credential_name})}),(0,s.jsx)(ev.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,s.jsx)(eb.default,{showSearch:!0,onChange:e=>{d(e),n.setFieldValue("custom_llm_provider",e)},children:Object.entries(ex.Cl).map(e=>{let[l,t]=e;return(0,s.jsx)(eb.default.Option,{value:l,children:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("img",{src:ex.cd[t],alt:"".concat(l," logo"),className:"w-5 h-5",onError:e=>{let l=e.target,s=l.parentElement;if(s){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=t.charAt(0),s.replaceChild(e,l)}}}),(0,s.jsx)("span",{children:t})]})},l)})})}),(0,s.jsx)(eF,{selectedProvider:o,uploadProps:r}),(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(L.Z,{title:"Get help on our github",children:(0,s.jsx)(eR,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(_.ZP,{onClick:()=>{t(),n.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,s.jsx)(_.ZP,{htmlType:"submit",children:"Update Credential"})]})]})]})})}var eO=e=>{var l;let{uploadProps:t}=e,{accessToken:r}=(0,n.Z)(),{data:i,refetch:o}=d(),c=(null==i?void 0:i.credentials)||[],[m,u]=(0,f.useState)(!1),[h,x]=(0,f.useState)(!1),[p,g]=(0,f.useState)(null),[j,v]=(0,f.useState)(null),[_,y]=(0,f.useState)(!1),[b,N]=(0,f.useState)(!1),[w]=ev.Z.useForm(),Z=["credential_name","custom_llm_provider"],C=async e=>{if(!r)return;let l=Object.entries(e).filter(e=>{let[l]=e;return!Z.includes(l)}).reduce((e,l)=>{let[t,s]=l;return{...e,[t]:s}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}};await (0,a.credentialUpdateCall)(r,e.credential_name,t),ec.ZP.success("Credential updated successfully"),x(!1),await o()},k=async e=>{if(!r)return;let l=Object.entries(e).filter(e=>{let[l]=e;return!Z.includes(l)}).reduce((e,l)=>{let[t,s]=l;return{...e,[t]:s}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}};await (0,a.credentialCreateCall)(r,t),ec.ZP.success("Credential added successfully"),u(!1),await o()},P=e=>{let l={openai:"blue",azure:"indigo",anthropic:"purple",default:"gray"},t=l[e.toLowerCase()]||l.default;return(0,s.jsx)(ej.Ct,{color:t,size:"xs",children:e})},A=async()=>{if(r&&j){N(!0);try{await (0,a.credentialDeleteCall)(r,j.credential_name),ec.ZP.success("Credential deleted successfully"),await o()}catch(e){ec.ZP.error("Failed to delete credential")}finally{v(null),y(!1),N(!1)}}},E=e=>{v(e),y(!0)};return(0,s.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto p-2",children:[(0,s.jsx)(ej.zx,{onClick:()=>u(!0),children:"Add Credential"}),(0,s.jsx)("div",{className:"flex justify-between items-center mt-4 mb-4",children:(0,s.jsx)(ej.xv,{children:"Configured credentials for different AI providers. Add and manage your API credentials."})}),(0,s.jsx)(ej.Zb,{children:(0,s.jsxs)(ej.iA,{children:[(0,s.jsx)(ej.ss,{children:(0,s.jsxs)(ej.SC,{children:[(0,s.jsx)(ej.xs,{children:"Credential Name"}),(0,s.jsx)(ej.xs,{children:"Provider"}),(0,s.jsx)(ej.xs,{children:"Actions"})]})}),(0,s.jsx)(ej.RM,{children:c&&0!==c.length?c.map((e,l)=>{var t;return(0,s.jsxs)(ej.SC,{children:[(0,s.jsx)(ej.pj,{children:e.credential_name}),(0,s.jsx)(ej.pj,{children:P((null===(t=e.credential_info)||void 0===t?void 0:t.custom_llm_provider)||"-")}),(0,s.jsxs)(ej.pj,{children:[(0,s.jsx)(ej.zx,{icon:ef.Z,variant:"light",size:"sm",onClick:()=>{g(e),x(!0)}}),(0,s.jsx)(ej.zx,{icon:S.Z,variant:"light",size:"sm",onClick:()=>E(e),className:"ml-2"})]})]},l)}):(0,s.jsx)(ej.SC,{children:(0,s.jsx)(ej.pj,{colSpan:4,className:"text-center py-4 text-gray-500",children:"No credentials configured"})})})]})}),m&&(0,s.jsx)(eT,{onAddCredential:k,open:m,onCancel:()=>u(!1),uploadProps:t}),h&&(0,s.jsx)(ez,{open:h,existingCredential:p,onUpdateCredential:C,uploadProps:t,onCancel:()=>x(!1)}),(0,s.jsx)(e_.Z,{isOpen:_,onCancel:()=>{v(null),y(!1)},onOk:A,title:"Delete Credential?",message:"Are you sure you want to delete this credential? This action cannot be undone and may break existing integrations.",resourceInformationTitle:"Credential Information",resourceInformation:[{label:"Credential Name",value:null==j?void 0:j.credential_name},{label:"Provider",value:(null==j?void 0:null===(l=j.credential_info)||void 0===l?void 0:l.custom_llm_provider)||"-"}],confirmLoading:b,requiredConfirmation:null==j?void 0:j.credential_name})]})},eV=t(20347),eq=t(23628),eD=t(29827),eB=t(49804),eG=t(12485),eU=t(18135),eH=t(35242),eK=t(77991),eJ=t(34419),eW=t(58643),eY=t(29),e$=t.n(eY),eX=t(23496),eQ=t(35291),e0=t(23639);let{Text:e1}=M.default;var e2=e=>{let{formValues:l,accessToken:t,testMode:r,modelName:i="this model",onClose:n,onTestComplete:o}=e,[d,c]=f.useState(null),[m,u]=f.useState(null),[h,x]=f.useState(null),[p,g]=f.useState(!0),[j,v]=f.useState(!1),[y,b]=f.useState(!1),N=async()=>{g(!0),b(!1),c(null),u(null),x(null),v(!1),await new Promise(e=>setTimeout(e,100));try{console.log("Testing connection with form values:",l);let r=await ep(l,t,null);if(!r){console.log("No result from prepareModelAddRequest"),c("Failed to prepare model data. Please check your form inputs."),v(!1),g(!1);return}console.log("Result from prepareModelAddRequest:",r);let{litellmParamsObj:i,modelInfoObj:n,modelName:o}=r[0],d=await (0,a.testConnectionRequest)(t,i,n,null==n?void 0:n.mode);if("success"===d.status)ec.ZP.success("Connection test successful!"),c(null),v(!0);else{var e,s;let l=(null===(e=d.result)||void 0===e?void 0:e.error)||d.message||"Unknown error";c(l),u(i),x(null===(s=d.result)||void 0===s?void 0:s.raw_request_typed_dict),v(!1)}}catch(e){console.error("Test connection error:",e),c(e instanceof Error?e.message:String(e)),v(!1)}finally{g(!1),o&&o()}};f.useEffect(()=>{let e=setTimeout(()=>{N()},200);return()=>clearTimeout(e)},[]);let w=e=>e?e.split("stack trace:")[0].trim().replace(/^litellm\.(.*?)Error: /,""):"Unknown error",Z="string"==typeof d?w(d):(null==d?void 0:d.message)?w(d.message):"Unknown error",C=h?((e,l,t)=>{let s=JSON.stringify(l,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(t).map(e=>{let[l,t]=e;return"-H '".concat(l,": ").concat(t,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(s,"\n }'")})(h.raw_request_api_base,h.raw_request_body,h.raw_request_headers||{}):"";return(0,s.jsxs)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:[p?(0,s.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},className:"jsx-dc9a0e2d897fe63b",children:[(0,s.jsx)("div",{style:{marginBottom:"16px"},className:"jsx-dc9a0e2d897fe63b loading-spinner",children:(0,s.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-dc9a0e2d897fe63b"})}),(0,s.jsxs)(e1,{style:{fontSize:"16px"},children:["Testing connection to ",i,"..."]}),(0,s.jsx)(e$(),{id:"dc9a0e2d897fe63b",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,s.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"32px 20px"},children:[(0,s.jsx)("div",{style:{color:"#52c41a",fontSize:"24px",display:"flex",alignItems:"center"},children:(0,s.jsx)("svg",{viewBox:"64 64 896 896",focusable:"false","data-icon":"check-circle",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",children:(0,s.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,s.jsxs)(e1,{type:"success",style:{fontSize:"18px",fontWeight:500,marginLeft:"10px"},children:["Connection to ",i," successful!"]})]}):(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",marginBottom:"20px"},children:[(0,s.jsx)(eQ.Z,{style:{color:"#ff4d4f",fontSize:"24px",marginRight:"12px"}}),(0,s.jsxs)(e1,{type:"danger",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",i," failed"]})]}),(0,s.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,s.jsxs)(e1,{strong:!0,style:{display:"block",marginBottom:"8px"},children:["Error:"," "]}),(0,s.jsx)(e1,{type:"danger",style:{fontSize:"14px",lineHeight:"1.5"},children:Z}),d&&(0,s.jsx)("div",{style:{marginTop:"12px"},children:(0,s.jsx)(_.ZP,{type:"link",onClick:()=>b(!y),style:{paddingLeft:0,height:"auto"},children:y?"Hide Details":"Show Details"})})]}),y&&(0,s.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,s.jsx)(e1,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"Troubleshooting Details"}),(0,s.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 d?d:JSON.stringify(d,null,2)})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(e1,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"API Request"}),(0,s.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"250px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:C||"No request data available"}),(0,s.jsx)(_.ZP,{style:{marginTop:"8px"},icon:(0,s.jsx)(e0.Z,{}),onClick:()=>{navigator.clipboard.writeText(C||""),ec.ZP.success("Copied to clipboard")},children:"Copy to Clipboard"})]})]})}),(0,s.jsx)(eX.Z,{style:{margin:"24px 0 16px"}}),(0,s.jsx)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:(0,s.jsx)(_.ZP,{type:"link",href:"https://docs.litellm.ai/docs/providers",target:"_blank",icon:(0,s.jsx)(q.Z,{}),children:"View Documentation"})})]})};let e4=async(e,l,t,s)=>{try{console.log("=== AUTO ROUTER SUBMIT HANDLER CALLED ==="),console.log("handling auto router submit for formValues:",e),console.log("Access token:",l?"Present":"Missing"),console.log("Form:",t?"Present":"Missing"),console.log("Callback:",s?"Present":"Missing");let r={model_name:e.auto_router_name,litellm_params:{model:"auto_router/".concat(e.auto_router_name),auto_router_config:JSON.stringify(e.auto_router_config),auto_router_default_model:e.auto_router_default_model},model_info:{}};e.auto_router_embedding_model&&"custom"!==e.auto_router_embedding_model?r.litellm_params.auto_router_embedding_model=e.auto_router_embedding_model:e.custom_embedding_model&&(r.litellm_params.auto_router_embedding_model=e.custom_embedding_model),e.team_id&&(r.model_info.team_id=e.team_id),e.model_access_group&&e.model_access_group.length>0&&(r.model_info.access_groups=e.model_access_group),console.log("Auto router configuration to be created:",r),console.log("Auto router config (stringified):",r.litellm_params.auto_router_config),console.log("Calling modelCreateCall with:",{accessToken:l?"Present":"Missing",config:r});let i=await (0,a.modelCreateCall)(l,r);console.log("response for auto router create call:",i),t.resetFields()}catch(e){console.error("Failed to add auto router:",e),ec.ZP.fromBackend("Failed to add auto router: "+e)}};var e5=t(10703),e6=t(44851),e3=t(96473),e8=t(70464),e7=t(26349),e9=t(92280);let{TextArea:le}=eA.default,{Panel:ll}=e6.default;var lt=e=>{let{modelInfo:l,value:t,onChange:a}=e,[r,i]=(0,f.useState)([]),[n,o]=(0,f.useState)(!1),[d,c]=(0,f.useState)([]);(0,f.useEffect)(()=>{if(null==t?void 0:t.routes){let e=t.routes.map((e,l)=>({id:e.id||"route-".concat(l,"-").concat(Date.now()),model:e.name||e.model||"",utterances:e.utterances||[],description:e.description||"",score_threshold:e.score_threshold||.5}));i(e),c(e.map(e=>e.id))}else i([]),c([])},[t]);let m=e=>{let l=r.filter(l=>l.id!==e);i(l),h(l),c(l=>l.filter(l=>l!==e))},u=(e,l,t)=>{let s=r.map(s=>s.id===e?{...s,[l]:t}:s);i(s),h(s)},h=e=>{let l={routes:e.map(e=>({name:e.model,utterances:e.utterances,description:e.description,score_threshold:e.score_threshold}))};null==a||a(l)},x=l.map(e=>({value:e.model_group,label:e.model_group}));return(0,s.jsxs)("div",{className:"w-full max-w-none",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-6 w-full",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(e9.x,{className:"text-lg font-semibold",children:"Routes Configuration"}),(0,s.jsx)(L.Z,{title:"Configure routing logic to automatically select the best model based on user input patterns",children:(0,s.jsx)(q.Z,{className:"text-gray-400"})})]}),(0,s.jsx)(_.ZP,{type:"primary",icon:(0,s.jsx)(e3.Z,{}),onClick:()=>{let e="route-".concat(Date.now()),l=[...r,{id:e,model:"",utterances:[],description:"",score_threshold:.5}];i(l),h(l),c(l=>[...l,e])},className:"bg-blue-600 hover:bg-blue-700",children:"Add Route"})]}),0===r.length?(0,s.jsx)("div",{className:"text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200 mb-6",children:(0,s.jsx)(e9.x,{children:"No routes configured. Click “Add Route” to get started."})}):(0,s.jsx)("div",{className:"space-y-3 mb-6 w-full",children:r.map((e,l)=>(0,s.jsx)(ea.Z,{className:"border border-gray-200 shadow-sm w-full",bodyStyle:{padding:0},children:(0,s.jsx)(e6.default,{ghost:!0,expandIcon:e=>{let{isActive:l}=e;return(0,s.jsx)(e8.Z,{rotate:l?180:0})},activeKey:d,onChange:e=>c(Array.isArray(e)?e:[e].filter(Boolean)),items:[{key:e.id,label:(0,s.jsxs)("div",{className:"flex justify-between items-center py-2",children:[(0,s.jsxs)(e9.x,{className:"font-medium text-base",children:["Route ",l+1,": ",e.model||"Unnamed"]}),(0,s.jsx)(_.ZP,{type:"text",danger:!0,icon:(0,s.jsx)(e7.Z,{}),onClick:l=>{l.stopPropagation(),m(e.id)},className:"mr-2"})]}),children:(0,s.jsxs)("div",{className:"px-6 pb-6 w-full",children:[(0,s.jsxs)("div",{className:"mb-4 w-full",children:[(0,s.jsx)(e9.x,{className:"text-sm font-medium mb-2 block",children:"Model"}),(0,s.jsx)(eb.default,{value:e.model,onChange:l=>u(e.id,"model",l),placeholder:"Select model",showSearch:!0,style:{width:"100%"},options:x})]}),(0,s.jsxs)("div",{className:"mb-4 w-full",children:[(0,s.jsx)(e9.x,{className:"text-sm font-medium mb-2 block",children:"Description"}),(0,s.jsx)(le,{value:e.description,onChange:l=>u(e.id,"description",l.target.value),placeholder:"Describe when this route should be used...",rows:2,style:{width:"100%"}})]}),(0,s.jsxs)("div",{className:"mb-4 w-full",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,s.jsx)(e9.x,{className:"text-sm font-medium",children:"Score Threshold"}),(0,s.jsx)(L.Z,{title:"Minimum similarity score to route to this model (0-1)",children:(0,s.jsx)(q.Z,{className:"text-gray-400"})})]}),(0,s.jsx)(ee.Z,{value:e.score_threshold,onChange:l=>u(e.id,"score_threshold",l||0),min:0,max:1,step:.1,style:{width:"100%"},placeholder:"0.5"})]}),(0,s.jsxs)("div",{className:"w-full",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,s.jsx)(e9.x,{className:"text-sm font-medium",children:"Example Utterances"}),(0,s.jsx)(L.Z,{title:"Training examples for this route. Type an utterance and press Enter to add it.",children:(0,s.jsx)(q.Z,{className:"text-gray-400"})})]}),(0,s.jsx)(e9.x,{className:"text-xs text-gray-500 mb-2",children:"Type an utterance and press Enter to add it. You can also paste multiple lines."}),(0,s.jsx)(eb.default,{mode:"tags",value:e.utterances,onChange:l=>u(e.id,"utterances",l),placeholder:"Type an utterance and press Enter...",style:{width:"100%"},tokenSeparators:["\n"],maxTagCount:"responsive",allowClear:!0})]})]})}]})},e.id))}),(0,s.jsxs)("div",{className:"border-t pt-6 w-full",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4 w-full",children:[(0,s.jsx)(e9.x,{className:"text-lg font-semibold",children:"JSON Preview"}),(0,s.jsx)(_.ZP,{type:"link",onClick:()=>o(!n),className:"text-blue-600 p-0",children:n?"Hide":"Show"})]}),n&&(0,s.jsx)(ea.Z,{className:"bg-gray-50 w-full",children:(0,s.jsx)("pre",{className:"text-sm overflow-auto max-h-64 w-full",children:JSON.stringify({routes:r.map(e=>({name:e.model,utterances:e.utterances,description:e.description,score_threshold:e.score_threshold}))},null,2)})})]})]})};let{Title:ls,Link:la}=M.default;var lr=e=>{let{form:l,handleOk:t,accessToken:r,userRole:i}=e,[n,o]=(0,f.useState)(!1),[d,c]=(0,f.useState)(!1),[m,u]=(0,f.useState)(""),[h,x]=(0,f.useState)([]),[p,g]=(0,f.useState)([]),[j,v]=(0,f.useState)(!1),[y,b]=(0,f.useState)(!1),[N,w]=(0,f.useState)(null);(0,f.useEffect)(()=>{(async()=>{x((await (0,a.modelAvailableCall)(r,"","",!1,null,!0,!0)).data.map(e=>e.id))})()},[r]),(0,f.useEffect)(()=>{(async()=>{try{let e=await (0,e5.p)(r);console.log("Fetched models for auto router:",e),g(e)}catch(e){console.error("Error fetching model info for auto router:",e)}})()},[r]);let Z=eV.ZL.includes(i),C=async()=>{c(!0),u("test-".concat(Date.now())),o(!0)},k=()=>{console.log("Auto router submit triggered!"),console.log("Router config:",N);let e=l.getFieldsValue();if(console.log("Form values:",e),!e.auto_router_name){ec.ZP.fromBackend("Please enter an Auto Router Name");return}if(!e.auto_router_default_model){ec.ZP.fromBackend("Please select a Default Model");return}if(l.setFieldsValue({custom_llm_provider:"auto_router",model:e.auto_router_name,api_key:"not_required_for_auto_router"}),!N||!N.routes||0===N.routes.length){ec.ZP.fromBackend("Please configure at least one route for the auto router");return}if(N.routes.filter(e=>!e.name||!e.description||0===e.utterances.length).length>0){ec.ZP.fromBackend("Please ensure all routes have a target model, description, and at least one utterance");return}l.validateFields().then(e=>{console.log("Form validation passed, submitting with values:",e);let s={...e,auto_router_config:N};console.log("Final submit values:",s),e4(s,r,l,t)}).catch(e=>{console.error("Validation failed:",e);let l=e.errorFields||[];if(l.length>0){let e=l.map(e=>{let l=e.name[0];return({auto_router_name:"Auto Router Name",auto_router_default_model:"Default Model",auto_router_embedding_model:"Embedding Model"})[l]||l});ec.ZP.fromBackend("Please fill in the following required fields: ".concat(e.join(", ")))}else ec.ZP.fromBackend("Please fill in all required fields")})};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(ls,{level:2,children:"Add Auto Router"}),(0,s.jsx)(eC.x,{className:"text-gray-600 mb-6",children:"Create an auto router with intelligent routing logic that automatically selects the best model based on user input patterns and semantic matching."}),(0,s.jsx)(ea.Z,{children:(0,s.jsxs)(ev.Z,{form:l,onFinish:k,labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(ev.Z.Item,{rules:[{required:!0,message:"Auto router name is required"}],label:"Auto Router Name",name:"auto_router_name",tooltip:"Unique name for this auto router configuration",labelCol:{span:10},labelAlign:"left",children:(0,s.jsx)(eC.o,{placeholder:"e.g., auto_router_1, smart_routing"})}),(0,s.jsx)("div",{className:"w-full mb-4",children:(0,s.jsx)(lt,{modelInfo:p,value:N,onChange:e=>{w(e),l.setFieldValue("auto_router_config",e)}})}),(0,s.jsx)(ev.Z.Item,{rules:[{required:!0,message:"Default model is required"}],label:"Default Model",name:"auto_router_default_model",tooltip:"Fallback model to use when auto routing logic cannot determine the best model",labelCol:{span:10},labelAlign:"left",children:(0,s.jsx)(eb.default,{placeholder:"Select a default model",onChange:e=>{v("custom"===e)},options:[...Array.from(new Set(p.map(e=>e.model_group))).map(e=>({value:e,label:e})),{value:"custom",label:"Enter custom model name"}],style:{width:"100%"},showSearch:!0})}),(0,s.jsx)(ev.Z.Item,{label:"Embedding Model",name:"auto_router_embedding_model",tooltip:"Optional: Embedding model to use for semantic routing decisions",labelCol:{span:10},labelAlign:"left",children:(0,s.jsx)(eb.default,{value:l.getFieldValue("auto_router_embedding_model"),placeholder:"Select an embedding model (optional)",onChange:e=>{b("custom"===e),l.setFieldValue("auto_router_embedding_model",e)},options:[...Array.from(new Set(p.map(e=>e.model_group))).map(e=>({value:e,label:e})),{value:"custom",label:"Enter custom model name"}],style:{width:"100%"},showSearch:!0,allowClear:!0})}),(0,s.jsxs)("div",{className:"flex items-center my-4",children:[(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,s.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Additional Settings"}),(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),Z&&(0,s.jsx)(ev.Z.Item,{label:"Model Access Group",name:"model_access_group",className:"mb-4",tooltip:"Use model access groups to control who can access this auto router",children:(0,s.jsx)(eb.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],options:h.map(e=>({value:e,label:e})),maxTagCount:"responsive",allowClear:!0})}),(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,s.jsx)(L.Z,{title:"Get help on our github",children:(0,s.jsx)(M.default.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{className:"space-x-2",children:[(0,s.jsx)(_.ZP,{onClick:C,loading:d,children:"Test Connect"}),(0,s.jsx)(_.ZP,{onClick:()=>{console.log("Add Auto Router button clicked!"),console.log("Current router config:",N),console.log("Current form values:",l.getFieldsValue()),k()},children:"Add Auto Router"})]})]})]})}),(0,s.jsx)(ei.Z,{title:"Connection Test Results",open:n,onCancel:()=>{o(!1),c(!1)},footer:[(0,s.jsx)(_.ZP,{onClick:()=>{o(!1),c(!1)},children:"Close"},"close")],width:700,children:n&&(0,s.jsx)(e2,{formValues:l.getFieldsValue(),accessToken:r,testMode:"chat",modelName:l.getFieldValue("auto_router_name"),onClose:()=>{o(!1),c(!1)},onTestComplete:()=>c(!1)},m)})]})};let li=(0,i.n)("guardrails"),ln=()=>{let{accessToken:e,userId:l,userRole:t}=(0,n.Z)();return(0,r.a)({queryKey:li.list({}),queryFn:async()=>(await (0,a.getGuardrailsList)(e)).guardrails.map(e=>e.guardrail_name),enabled:!!(e&&l&&t)})},lo=(0,i.n)("tags"),ld=()=>{let{accessToken:e,userId:l,userRole:t}=(0,n.Z)();return(0,r.a)({queryKey:lo.list({}),queryFn:async()=>await (0,a.tagListCall)(e),enabled:!!(e&&l&&t)})};var lc=t(59341),lm=t(51653),lu=t(84376),lh=t(63709),lx=t(26210),lp=t(34766),lg=t(45246),lf=t(24199);let{Text:lj}=M.default;var lv=e=>{let{form:l,showCacheControl:t,onCacheControlChange:a}=e,r=e=>{let t=l.getFieldValue("litellm_extra_params");try{let s=t?JSON.parse(t):{};e.length>0?s.cache_control_injection_points=e:delete s.cache_control_injection_points,Object.keys(s).length>0?l.setFieldValue("litellm_extra_params",JSON.stringify(s,null,2)):l.setFieldValue("litellm_extra_params","")}catch(e){console.error("Error updating cache control points:",e)}};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(ev.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,s.jsx)(lh.Z,{onChange:a,className:"bg-gray-600"})}),t&&(0,s.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,s.jsx)(lj,{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,s.jsx)(ev.Z.List,{name:"cache_control_injection_points",initialValue:[{location:"message"}],children:(e,t)=>{let{add:a,remove:i}=t;return(0,s.jsxs)(s.Fragment,{children:[e.map((t,a)=>(0,s.jsxs)("div",{className:"flex items-center mb-4 gap-4",children:[(0,s.jsx)(ev.Z.Item,{...t,label:"Type",name:[t.name,"location"],initialValue:"message",className:"mb-0",style:{width:"180px"},children:(0,s.jsx)(eb.default,{disabled:!0,options:[{value:"message",label:"Message"}]})}),(0,s.jsx)(ev.Z.Item,{...t,label:"Role",name:[t.name,"role"],className:"mb-0",style:{width:"180px"},tooltip:"LiteLLM will mark all messages of this role as cacheable",children:(0,s.jsx)(eb.default,{placeholder:"Select a role",allowClear:!0,options:[{value:"user",label:"User"},{value:"system",label:"System"},{value:"assistant",label:"Assistant"}],onChange:()=>{r(l.getFieldValue("cache_control_points"))}})}),(0,s.jsx)(ev.Z.Item,{...t,label:"Index",name:[t.name,"index"],className:"mb-0",style:{width:"180px"},tooltip:"(Optional) If set litellm will mark the message at this index as cacheable",children:(0,s.jsx)(lf.Z,{type:"number",placeholder:"Optional",step:1,onChange:()=>{r(l.getFieldValue("cache_control_points"))}})}),e.length>1&&(0,s.jsx)(lg.Z,{className:"text-red-500 cursor-pointer text-lg ml-12",onClick:()=>{i(t.name),setTimeout(()=>{r(l.getFieldValue("cache_control_points"))},0)}})]},t.key)),(0,s.jsx)(ev.Z.Item,{children:(0,s.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:()=>a(),children:[(0,s.jsx)(e3.Z,{className:"mr-2"}),"Add Injection Point"]})})]})}})]})]})},l_=t(9309);let{Link:ly}=M.default;var lb=e=>{let{showAdvancedSettings:l,setShowAdvancedSettings:t,teams:a,guardrailsList:r,tagsList:i}=e,[n]=ev.Z.useForm(),[o,d]=f.useState(!1),[c,m]=f.useState("per_token"),[u,h]=f.useState(!1),x=(e,l)=>l&&(isNaN(Number(l))||0>Number(l))?Promise.reject("Please enter a valid positive number"):Promise.resolve();return(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)(lx.UQ,{className:"mt-2 mb-4",children:[(0,s.jsx)(lx._m,{children:(0,s.jsx)("b",{children:"Advanced Settings"})}),(0,s.jsx)(lx.X1,{children:(0,s.jsxs)("div",{className:"bg-white rounded-lg",children:[(0,s.jsx)(ev.Z.Item,{label:"Custom Pricing",name:"custom_pricing",valuePropName:"checked",className:"mb-4",children:(0,s.jsx)(lh.Z,{onChange:e=>{d(e),e||n.setFieldsValue({input_cost_per_token:void 0,output_cost_per_token:void 0,input_cost_per_second:void 0})},className:"bg-gray-600"})}),(0,s.jsx)(ev.Z.Item,{label:(0,s.jsxs)("span",{children:["Guardrails"," ",(0,s.jsx)(L.Z,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(q.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:"Select existing guardrails. Go to 'Guardrails' tab to create new guardrails.",children:(0,s.jsx)(eb.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:r.map(e=>({value:e,label:e}))})}),(0,s.jsx)(ev.Z.Item,{label:"Tags",name:"tags",className:"mb-4",children:(0,s.jsx)(eb.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter tags",options:Object.values(i).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}),o&&(0,s.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,s.jsx)(ev.Z.Item,{label:"Pricing Model",name:"pricing_model",className:"mb-4",children:(0,s.jsx)(eb.default,{defaultValue:"per_token",onChange:e=>m(e),options:[{value:"per_token",label:"Per Million Tokens"},{value:"per_second",label:"Per Second"}]})}),"per_token"===c?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(ev.Z.Item,{label:"Input Cost (per 1M tokens)",name:"input_cost_per_token",rules:[{validator:x}],className:"mb-4",children:(0,s.jsx)(lx.oi,{})}),(0,s.jsx)(ev.Z.Item,{label:"Output Cost (per 1M tokens)",name:"output_cost_per_token",rules:[{validator:x}],className:"mb-4",children:(0,s.jsx)(lx.oi,{})})]}):(0,s.jsx)(ev.Z.Item,{label:"Cost Per Second",name:"input_cost_per_second",rules:[{validator:x}],className:"mb-4",children:(0,s.jsx)(lx.oi,{})})]}),(0,s.jsx)(ev.Z.Item,{label:"Use in pass through routes",name:"use_in_pass_through",valuePropName:"checked",className:"mb-4 mt-4",tooltip:(0,s.jsxs)("span",{children:["Allow using these credentials in pass through routes."," ",(0,s.jsx)(ly,{href:"https://docs.litellm.ai/docs/pass_through/vertex_ai",target:"_blank",children:"Learn more"})]}),children:(0,s.jsx)(lh.Z,{onChange:e=>{let l=n.getFieldValue("litellm_extra_params");try{let t=l?JSON.parse(l):{};e?t.use_in_pass_through=!0:delete t.use_in_pass_through,Object.keys(t).length>0?n.setFieldValue("litellm_extra_params",JSON.stringify(t,null,2)):n.setFieldValue("litellm_extra_params","")}catch(l){e?n.setFieldValue("litellm_extra_params",JSON.stringify({use_in_pass_through:!0},null,2)):n.setFieldValue("litellm_extra_params","")}},className:"bg-gray-600"})}),(0,s.jsx)(lv,{form:n,showCacheControl:u,onCacheControlChange:e=>{if(h(e),!e){let e=n.getFieldValue("litellm_extra_params");try{let l=e?JSON.parse(e):{};delete l.cache_control_injection_points,Object.keys(l).length>0?n.setFieldValue("litellm_extra_params",JSON.stringify(l,null,2)):n.setFieldValue("litellm_extra_params","")}catch(e){n.setFieldValue("litellm_extra_params","")}}}}),(0,s.jsx)(ev.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:l_.Ac}],children:(0,s.jsx)(lp.Z,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}),(0,s.jsxs)(ek.Z,{className:"mb-4",children:[(0,s.jsx)(eS.Z,{span:10}),(0,s.jsx)(eS.Z,{span:10,children:(0,s.jsxs)(lx.xv,{className:"text-gray-600 text-sm",children:["Pass JSON of litellm supported params"," ",(0,s.jsx)(ly,{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",children:"litellm.completion() call"})]})})]}),(0,s.jsx)(ev.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:l_.Ac}],children:(0,s.jsx)(lp.Z,{rows:4,placeholder:'{ "mode": "chat" }'})})]})})]})})},lN=t(56609),lw=t(67187);let lZ=e=>{let{content:l,children:t,width:a="auto",className:r=""}=e,[i,n]=(0,f.useState)(!1),[o,d]=(0,f.useState)("top"),c=(0,f.useRef)(null),m=()=>{if(c.current){let e=c.current.getBoundingClientRect(),l=e.top,t=window.innerHeight-e.bottom;l<300&&t>300?d("bottom"):d("top")}};return(0,s.jsxs)("div",{className:"relative inline-block",ref:c,children:[t||(0,s.jsx)(lw.Z,{className:"ml-1 text-gray-500 cursor-help",onMouseEnter:()=>{m(),n(!0)},onMouseLeave:()=>n(!1)}),i&&(0,s.jsxs)("div",{className:"absolute left-1/2 -translate-x-1/2 z-50 bg-black/90 text-white p-2 rounded-md text-sm font-normal shadow-lg ".concat(r),style:{["top"===o?"bottom":"top"]:"100%",width:a,marginBottom:"top"===o?"8px":"0",marginTop:"bottom"===o?"8px":"0"},children:[l,(0,s.jsx)("div",{className:"absolute left-1/2 -translate-x-1/2 w-0 h-0",style:{top:"top"===o?"100%":"auto",bottom:"bottom"===o?"100%":"auto",borderTop:"top"===o?"6px solid rgba(0, 0, 0, 0.9)":"6px solid transparent",borderBottom:"bottom"===o?"6px solid rgba(0, 0, 0, 0.9)":"6px solid transparent",borderLeft:"6px solid transparent",borderRight:"6px solid transparent"}})]})]})};var lC=()=>{let e=ev.Z.useFormInstance(),[l,t]=(0,f.useState)(0),a=ev.Z.useWatch("model",e)||[],r=Array.isArray(a)?a:[a],i=ev.Z.useWatch("custom_model_name",e),n=!r.includes("all-wildcard"),o=ev.Z.useWatch("custom_llm_provider",e);if((0,f.useEffect)(()=>{if(i&&r.includes("custom")){let l=(e.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?o===ex.Cl.Azure?{public_name:i,litellm_model:"azure/".concat(i)}:{public_name:i,litellm_model:i}:e);e.setFieldValue("model_mappings",l),t(e=>e+1)}},[i,r,o,e]),(0,f.useEffect)(()=>{if(r.length>0&&!r.includes("all-wildcard")){let l=e.getFieldValue("model_mappings")||[];if(l.length!==r.length||!r.every(e=>l.some(l=>"custom"===e?"custom"===l.litellm_model||l.litellm_model===i:o===ex.Cl.Azure?l.litellm_model==="azure/".concat(e):l.litellm_model===e))){let l=r.map(e=>"custom"===e&&i?o===ex.Cl.Azure?{public_name:i,litellm_model:"azure/".concat(i)}:{public_name:i,litellm_model:i}:o===ex.Cl.Azure?{public_name:e,litellm_model:"azure/".concat(e)}:{public_name:e,litellm_model:e});e.setFieldValue("model_mappings",l),t(e=>e+1)}}},[r,i,o,e]),!n)return null;let d=(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{className:"mb-2 font-normal",children:"The name you specify in your API calls to LiteLLM Proxy"}),(0,s.jsxs)("div",{className:"mb-2 font-normal",children:[(0,s.jsx)("strong",{children:"Example:"})," If you name your public model"," ",(0,s.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"example-name"}),", and choose"," ",(0,s.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"openai/qwen-plus-latest"})," as the LiteLLM model"]}),(0,s.jsxs)("div",{className:"mb-2 font-normal",children:[(0,s.jsx)("strong",{children:"Usage:"})," You make an API call to the LiteLLM proxy with"," ",(0,s.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:'model = "example-name"'})]}),(0,s.jsxs)("div",{className:"font-normal",children:[(0,s.jsx)("strong",{children:"Result:"})," LiteLLM sends"," ",(0,s.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"qwen-plus-latest"})," to the provider"]})]}),c=(0,s.jsx)("div",{children:"The model name LiteLLM will send to the LLM API"}),m=[{title:(0,s.jsxs)("span",{className:"flex items-center",children:["Public Model Name",(0,s.jsx)(lZ,{content:d,width:"500px"})]}),dataIndex:"public_name",key:"public_name",render:(l,t,a)=>(0,s.jsx)(ey.o,{value:l,onChange:l=>{let t=l.target.value,s=[...e.getFieldValue("model_mappings")],r=o===ex.Cl.Anthropic,i=t.endsWith("-1m"),n=e.getFieldValue("litellm_extra_params"),d=!n||""===n.trim(),c=t;if(r&&i&&d){let l=JSON.stringify({extra_headers:{"anthropic-beta":"context-1m-2025-08-07"}},null,2);e.setFieldValue("litellm_extra_params",l),c=t.slice(0,-3)}s[a].public_name=c,e.setFieldValue("model_mappings",s)}})},{title:(0,s.jsxs)("span",{className:"flex items-center",children:["LiteLLM Model Name",(0,s.jsx)(lZ,{content:c,width:"360px"})]}),dataIndex:"litellm_model",key:"litellm_model"}];return(0,s.jsx)(s.Fragment,{children:(0,s.jsx)(ev.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",rules:[{required:!0,validator:async(e,l)=>{if(!l||0===l.length)throw Error("At least one model mapping is required");if(l.filter(e=>!e.public_name||""===e.public_name.trim()).length>0)throw Error("All model mappings must have valid public names")}}],children:(0,s.jsx)(lN.Z,{dataSource:e.getFieldValue("model_mappings"),columns:m,pagination:!1,size:"small"},l)})})},lk=e=>{let{selectedProvider:l,providerModels:t,getPlaceholder:a}=e,r=ev.Z.useFormInstance(),i=e=>{let t=e.target.value,s=(r.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?l===ex.Cl.Azure?{public_name:t,litellm_model:"azure/".concat(t)}:{public_name:t,litellm_model:t}:e);r.setFieldsValue({model_mappings:s})};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)(ev.Z.Item,{label:"LiteLLM Model Name(s)",tooltip:"The model name LiteLLM will send to the LLM API",className:"mb-0",children:[(0,s.jsx)(ev.Z.Item,{name:"model",rules:[{required:!0,message:"Please enter ".concat(l===ex.Cl.Azure?"a deployment name":"at least one model",".")}],noStyle:!0,children:l===ex.Cl.Azure||l===ex.Cl.OpenAI_Compatible||l===ex.Cl.Ollama?(0,s.jsx)(s.Fragment,{children:(0,s.jsx)(eC.o,{placeholder:a(l),onChange:l===ex.Cl.Azure?e=>{let l=e.target.value,t=l?[{public_name:l,litellm_model:"azure/".concat(l)}]:[];r.setFieldsValue({model:l,model_mappings:t})}:void 0})}):t.length>0?(0,s.jsx)(eb.default,{mode:"multiple",allowClear:!0,showSearch:!0,placeholder:"Select models",onChange:e=>{let t=Array.isArray(e)?e:[e];if(t.includes("all-wildcard"))r.setFieldsValue({model_name:void 0,model_mappings:[]});else if(JSON.stringify(r.getFieldValue("model"))!==JSON.stringify(t)){let e=t.map(e=>l===ex.Cl.Azure?{public_name:e,litellm_model:"azure/".concat(e)}:{public_name:e,litellm_model:e});r.setFieldsValue({model:t,model_mappings:e})}},optionFilterProp:"children",filterOption:(e,l)=>{var t;return(null!==(t=null==l?void 0:l.label)&&void 0!==t?t:"").toLowerCase().includes(e.toLowerCase())},options:[{label:"Custom Model Name (Enter below)",value:"custom"},{label:"All ".concat(l," Models (Wildcard)"),value:"all-wildcard"},...t.map(e=>({label:e,value:e}))],style:{width:"100%"}}):(0,s.jsx)(eC.o,{placeholder:a(l)})}),(0,s.jsx)(ev.Z.Item,{noStyle:!0,shouldUpdate:(e,l)=>e.model!==l.model,children:e=>{let{getFieldValue:t}=e,a=t("model")||[];return(Array.isArray(a)?a:[a]).includes("custom")&&(0,s.jsx)(ev.Z.Item,{name:"custom_model_name",rules:[{required:!0,message:"Please enter a custom model name."}],className:"mt-2",children:(0,s.jsx)(eC.o,{placeholder:l===ex.Cl.Azure?"Enter Azure deployment name":"Enter custom model name",onChange:i})})}})]}),(0,s.jsxs)(ek.Z,{children:[(0,s.jsx)(eS.Z,{span:10}),(0,s.jsx)(eS.Z,{span:14,children:(0,s.jsx)(eC.x,{className:"mb-3 mt-1",children:l===ex.Cl.Azure?"Your deployment name will be saved as the public model name, and LiteLLM will use 'azure/deployment-name' internally":"The model name LiteLLM will send to the LLM API"})})]})]})};let lS=[{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:"video_generation",label:"Video Generation - /videos"},{value:"rerank",label:"Rerank - /rerank"},{value:"realtime",label:"Realtime - /realtime"},{value:"batch",label:"Batch - /batch"},{value:"ocr",label:"OCR - /ocr"}],{Title:lP,Link:lA}=M.default;var lE=e=>{let{form:l,handleOk:t,selectedProvider:r,setSelectedProvider:i,providerModels:o,setProviderModelsFn:d,getPlaceholder:c,uploadProps:m,showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x,credentials:p}=e,[g,j]=(0,f.useState)("chat"),[v,y]=(0,f.useState)(!1),[b,N]=(0,f.useState)(!1),[w,Z]=(0,f.useState)(""),{accessToken:C,userRole:k,premiumUser:S,userId:P}=(0,n.Z)(),{data:A,isLoading:E,error:F}=ew(),{data:I,isLoading:T,error:z}=ln(),{data:O,isLoading:V,error:q}=ld(),D=async()=>{N(!0),Z("test-".concat(Date.now())),y(!0)},[B,G]=(0,f.useState)(!1),[U,K]=(0,f.useState)([]),[J,W]=(0,f.useState)(null);(0,f.useEffect)(()=>{(async()=>{K((await (0,a.modelAvailableCall)(C,"","",!1,null,!0,!0)).data.map(e=>e.id))})()},[C]);let Y=(0,f.useMemo)(()=>A?[...A].sort((e,l)=>e.provider_display_name.localeCompare(l.provider_display_name)):[],[A]),$=F?F instanceof Error?F.message:"Failed to load providers":null,X=eV.ZL.includes(k),Q=(0,eV.yV)(x,P);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(lP,{level:2,children:"Add Model"}),(0,s.jsx)(ea.Z,{children:(0,s.jsx)(ev.Z,{form:l,onFinish:async e=>{console.log("\uD83D\uDD25 Form onFinish triggered with values:",e),await t().then(()=>{W(null)})},onFinishFailed:e=>{console.log("\uD83D\uDCA5 Form onFinishFailed triggered:",e)},labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:(0,s.jsxs)(s.Fragment,{children:[Q&&!X&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(ev.Z.Item,{label:"Select Team",name:"team_id",rules:[{required:!0,message:"Please select a team to continue"}],tooltip:"Select the team for which you want to add this model",children:(0,s.jsx)(lu.Z,{teams:x,onChange:e=>{W(e)}})}),!J&&(0,s.jsx)(lm.Z,{message:"Team Selection Required",description:"As a team admin, you need to select your team first before adding models.",type:"info",showIcon:!0,className:"mb-4"})]}),(X||Q&&J)&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(ev.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,s.jsxs)(eb.default,{virtual:!1,showSearch:!0,loading:E,placeholder:E?"Loading providers...":"Select a provider",optionFilterProp:"data-label",onChange:e=>{i(e),d(e),l.setFieldsValue({custom_llm_provider:e}),l.setFieldsValue({model:[],model_name:void 0})},children:[$&&0===Y.length&&(0,s.jsx)(eb.default.Option,{value:"",children:$},"__error"),Y.map(e=>{let l=e.provider_display_name,t=e.provider;return ex.cd[l],(0,s.jsx)(eb.default.Option,{value:t,"data-label":l,children:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)(R.K,{provider:t,className:"w-5 h-5"}),(0,s.jsx)("span",{children:l})]})},t)})]})}),(0,s.jsx)(lk,{selectedProvider:r,providerModels:o,getPlaceholder:c}),(0,s.jsx)(lC,{}),(0,s.jsx)(ev.Z.Item,{label:"Mode",name:"mode",className:"mb-1",children:(0,s.jsx)(eb.default,{style:{width:"100%"},value:g,onChange:e=>j(e),options:lS})}),(0,s.jsxs)(ek.Z,{children:[(0,s.jsx)(eS.Z,{span:10}),(0,s.jsx)(eS.Z,{span:10,children:(0,s.jsxs)(H.Z,{className:"mb-5 mt-1",children:[(0,s.jsx)("strong",{children:"Optional"})," - LiteLLM endpoint to use when health checking this model"," ",(0,s.jsx)(lA,{href:"https://docs.litellm.ai/docs/proxy/health#health",target:"_blank",children:"Learn more"})]})})]}),(0,s.jsx)("div",{className:"mb-4",children:(0,s.jsx)(M.default.Text,{className:"text-sm text-gray-500 mb-2",children:"Either select existing credentials OR enter new provider credentials below"})}),(0,s.jsx)(ev.Z.Item,{label:"Existing Credentials",name:"litellm_credential_name",initialValue:null,children:(0,s.jsx)(eb.default,{showSearch:!0,placeholder:"Select or search for existing credentials",optionFilterProp:"children",filterOption:(e,l)=>{var t;return(null!==(t=null==l?void 0:l.label)&&void 0!==t?t:"").toLowerCase().includes(e.toLowerCase())},options:[{value:null,label:"None"},...p.map(e=>({value:e.credential_name,label:e.credential_name}))],allowClear:!0})}),(0,s.jsx)(ev.Z.Item,{noStyle:!0,shouldUpdate:(e,l)=>e.litellm_credential_name!==l.litellm_credential_name||e.provider!==l.provider,children:e=>{let{getFieldValue:l}=e,t=l("litellm_credential_name");return(console.log("\uD83D\uDD11 Credential Name Changed:",t),t)?null:(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{className:"flex items-center my-4",children:[(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,s.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"OR"}),(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,s.jsx)(eF,{selectedProvider:r,uploadProps:m})]})}}),(0,s.jsxs)("div",{className:"flex items-center my-4",children:[(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,s.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Additional Model Info Settings"}),(0,s.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(X||!Q)&&(0,s.jsx)(ev.Z.Item,{label:"Team-BYOK Model",tooltip:"Only use this model + credential combination for this team. Useful when teams want to onboard their own OpenAI keys.",className:"mb-4",children:(0,s.jsx)(L.Z,{title:S?"":"This is an enterprise-only feature. Upgrade to premium to restrict model+credential combinations to a specific team.",placement:"top",children:(0,s.jsx)(lc.Z,{checked:B,onChange:e=>{G(e),e||l.setFieldValue("team_id",void 0)},disabled:!S})})}),B&&(X||!Q)&&(0,s.jsx)(ev.Z.Item,{label:"Select Team",name:"team_id",className:"mb-4",tooltip:"Only keys for this team will be able to call this model.",rules:[{required:B&&!X,message:"Please select a team."}],children:(0,s.jsx)(lu.Z,{teams:x,disabled:!S})}),X&&(0,s.jsx)(s.Fragment,{children:(0,s.jsx)(ev.Z.Item,{label:"Model Access Group",name:"model_access_group",className:"mb-4",tooltip:"Use model access groups to give users access to select models, and add new ones to the group over time.",children:(0,s.jsx)(eb.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],options:U.map(e=>({value:e,label:e})),maxTagCount:"responsive",allowClear:!0})})}),(0,s.jsx)(lb,{showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x,guardrailsList:I||[],tagsList:O||{}})]}),(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,s.jsx)(L.Z,{title:"Get help on our github",children:(0,s.jsx)(M.default.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{className:"space-x-2",children:[(0,s.jsx)(_.ZP,{onClick:D,loading:b,children:"Test Connect"}),(0,s.jsx)(_.ZP,{htmlType:"submit",children:"Add Model"})]})]})]})})}),(0,s.jsx)(ei.Z,{title:"Connection Test Results",open:v,onCancel:()=>{y(!1),N(!1)},footer:[(0,s.jsx)(_.ZP,{onClick:()=>{y(!1),N(!1)},children:"Close"},"close")],width:700,children:v&&(0,s.jsx)(e2,{formValues:l.getFieldsValue(),accessToken:C,testMode:g,modelName:l.getFieldValue("model_name")||l.getFieldValue("model"),onClose:()=>{y(!1),N(!1)},onTestComplete:()=>N(!1)},w)})]})},lM=e=>{let{form:l,handleOk:t,selectedProvider:a,setSelectedProvider:r,providerModels:i,setProviderModelsFn:n,getPlaceholder:o,uploadProps:d,showAdvancedSettings:c,setShowAdvancedSettings:m,teams:u,credentials:h,accessToken:x,userRole:p}=e,[g]=ev.Z.useForm();return(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)(eW.v0,{className:"w-full",children:[(0,s.jsxs)(eW.td,{className:"mb-4",children:[(0,s.jsx)(eW.OK,{children:"Add Model"}),(0,s.jsx)(eW.OK,{children:"Add Auto Router"})]}),(0,s.jsxs)(eW.nP,{children:[(0,s.jsx)(eW.x4,{children:(0,s.jsx)(lE,{form:l,handleOk:t,selectedProvider:a,setSelectedProvider:r,providerModels:i,setProviderModelsFn:n,getPlaceholder:o,uploadProps:d,showAdvancedSettings:c,setShowAdvancedSettings:m,teams:u,credentials:h})}),(0,s.jsx)(eW.x4,{children:(0,s.jsx)(lr,{form:g,handleOk:()=>{g.validateFields().then(e=>{e4(e,x,g,t)}).catch(e=>{console.error("Validation failed:",e)})},accessToken:x,userRole:p})})]})]})})},lL=t(8048),lF=t(4156),lI=t(15731),lT=t(91126);let lR=(e,l,t,a,r,i,n,o,d,c,m,u)=>[{header:()=>(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(lF.Z,{checked:t,indeterminate:l.length>0&&!t,onChange:e=>r(e.target.checked),onClick:e=>e.stopPropagation()}),(0,s.jsx)("span",{children:"Model ID"})]}),accessorKey:"model_info.id",enableSorting:!0,sortingFn:"alphanumeric",cell:e=>{let{row:t}=e,r=t.original,i=r.model_name,n=l.includes(i);return(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(lF.Z,{checked:n,onChange:e=>a(i,e.target.checked),onClick:e=>e.stopPropagation()}),(0,s.jsx)(L.Z,{title:r.model_info.id,children:(0,s.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 max-w-[15ch]",onClick:()=>m&&m(r.model_info.id),children:r.model_info.id})})]})}},{header:"Model Name",accessorKey:"model_name",enableSorting:!0,sortingFn:"alphanumeric",cell:e=>{let{row:l}=e,t=l.original,a=o(t)||t.model_name;return(0,s.jsx)("div",{className:"font-medium text-sm",children:(0,s.jsx)(L.Z,{title:a,children:(0,s.jsx)("div",{className:"truncate max-w-[200px]",children:a})})})}},{header:"Team Alias",accessorKey:"model_info.team_id",enableSorting:!0,sortingFn:"alphanumeric",cell:e=>{var l;let{row:t}=e,a=null===(l=t.original.model_info)||void 0===l?void 0:l.team_id;if(!a)return(0,s.jsx)("span",{className:"text-gray-400 text-sm",children:"-"});let r=null==u?void 0:u.find(e=>e.team_id===a),i=(null==r?void 0:r.team_alias)||a;return(0,s.jsx)("div",{className:"text-sm",children:(0,s.jsx)(L.Z,{title:i,children:(0,s.jsx)("div",{className:"truncate max-w-[150px]",children:i})})})}},{header:"Health Status",accessorKey:"health_status",enableSorting:!0,sortingFn:(e,l,t)=>{var s,a;let r=e.getValue("health_status")||"unknown",i=l.getValue("health_status")||"unknown",n={healthy:0,checking:1,unknown:2,unhealthy:3};return(null!==(s=n[r])&&void 0!==s?s:4)-(null!==(a=n[i])&&void 0!==a?a:4)},cell:l=>{var t;let{row:a}=l,r=a.original,i={status:r.health_status,loading:r.health_loading,error:r.health_error};if(i.loading)return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsxs)("div",{className:"flex space-x-1",children:[(0,s.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse"}),(0,s.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse",style:{animationDelay:"0.2s"}}),(0,s.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse",style:{animationDelay:"0.4s"}})]}),(0,s.jsx)(e9.x,{className:"text-gray-600 text-sm",children:"Checking..."})]});let o=r.model_name,d="healthy"===i.status&&(null===(t=e[o])||void 0===t?void 0:t.successResponse);return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[n(i.status),d&&c&&(0,s.jsx)(L.Z,{title:"View response details",placement:"top",children:(0,s.jsx)("button",{onClick:()=>{var l;return c(o,null===(l=e[o])||void 0===l?void 0:l.successResponse)},className:"p-1 text-green-600 hover:text-green-800 hover:bg-green-50 rounded cursor-pointer transition-colors",children:(0,s.jsx)(lI.Z,{className:"h-4 w-4"})})})]})}},{header:"Error Details",accessorKey:"health_error",enableSorting:!1,cell:l=>{let{row:t}=l,a=t.original.model_name,r=e[a];if(!(null==r?void 0:r.error))return(0,s.jsx)(e9.x,{className:"text-gray-400 text-sm",children:"No errors"});let i=r.error,n=r.fullError||r.error;return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("div",{className:"max-w-[200px]",children:(0,s.jsx)(L.Z,{title:i,placement:"top",children:(0,s.jsx)(e9.x,{className:"text-red-600 text-sm truncate",children:i})})}),d&&n!==i&&(0,s.jsx)(L.Z,{title:"View full error details",placement:"top",children:(0,s.jsx)("button",{onClick:()=>d(a,i,n),className:"p-1 text-red-600 hover:text-red-800 hover:bg-red-50 rounded cursor-pointer transition-colors",children:(0,s.jsx)(lI.Z,{className:"h-4 w-4"})})})]})}},{header:"Last Check",accessorKey:"last_check",enableSorting:!0,sortingFn:(e,l,t)=>{let s=e.getValue("last_check")||"Never checked",a=l.getValue("last_check")||"Never checked";if("Never checked"===s&&"Never checked"===a)return 0;if("Never checked"===s)return 1;if("Never checked"===a)return -1;if("Check in progress..."===s&&"Check in progress..."===a)return 0;if("Check in progress..."===s)return -1;if("Check in progress..."===a)return 1;let r=new Date(s),i=new Date(a);return isNaN(r.getTime())&&isNaN(i.getTime())?0:isNaN(r.getTime())?1:isNaN(i.getTime())?-1:i.getTime()-r.getTime()},cell:e=>{let{row:l}=e,t=l.original;return(0,s.jsx)(e9.x,{className:"text-gray-600 text-sm",children:t.health_loading?"Check in progress...":t.last_check})}},{header:"Last Success",accessorKey:"last_success",enableSorting:!0,sortingFn:(e,l,t)=>{let s=e.getValue("last_success")||"Never succeeded",a=l.getValue("last_success")||"Never succeeded";if("Never succeeded"===s&&"Never succeeded"===a)return 0;if("Never succeeded"===s)return 1;if("Never succeeded"===a)return -1;if("None"===s&&"None"===a)return 0;if("None"===s)return 1;if("None"===a)return -1;let r=new Date(s),i=new Date(a);return isNaN(r.getTime())&&isNaN(i.getTime())?0:isNaN(r.getTime())?1:isNaN(i.getTime())?-1:i.getTime()-r.getTime()},cell:l=>{let{row:t}=l,a=e[t.original.model_name],r=(null==a?void 0:a.lastSuccess)||"None";return(0,s.jsx)(e9.x,{className:"text-gray-600 text-sm",children:r})}},{header:"Actions",id:"actions",cell:e=>{let{row:l}=e,t=l.original,a=t.model_name,r=t.health_status&&"none"!==t.health_status,n=t.health_loading?"Checking...":r?"Re-run Health Check":"Run Health Check";return(0,s.jsx)(L.Z,{title:n,placement:"top",children:(0,s.jsx)("button",{className:"p-2 rounded-md transition-colors ".concat(t.health_loading?"text-gray-400 cursor-not-allowed bg-gray-100":"text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50"),onClick:()=>{t.health_loading||i(a)},disabled:t.health_loading,children:t.health_loading?(0,s.jsxs)("div",{className:"flex space-x-1",children:[(0,s.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse"}),(0,s.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse",style:{animationDelay:"0.2s"}}),(0,s.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse",style:{animationDelay:"0.4s"}})]}):r?(0,s.jsx)(eq.Z,{className:"h-4 w-4"}):(0,s.jsx)(lT.Z,{className:"h-4 w-4"})})})},enableSorting:!1}],lz=[{pattern:/Missing .* API Key/i,replacement:"Missing API Key"},{pattern:/Connection timeout/i,replacement:"Connection timeout"},{pattern:/Network.*not.*ok/i,replacement:"Network connection failed"},{pattern:/403.*Forbidden/i,replacement:"Access forbidden - check API key permissions"},{pattern:/401.*Unauthorized/i,replacement:"Unauthorized - invalid API key"},{pattern:/429.*rate limit/i,replacement:"Rate limit exceeded"},{pattern:/500.*Internal Server Error/i,replacement:"Provider internal server error"},{pattern:/litellm\.AuthenticationError/i,replacement:"Authentication failed"},{pattern:/litellm\.RateLimitError/i,replacement:"Rate limit exceeded"},{pattern:/litellm\.APIError/i,replacement:"API error"}];var lO=e=>{let{accessToken:l,modelData:t,all_models_on_proxy:r,getDisplayModelName:i,setSelectedModelId:n,teams:o}=e,[d,c]=(0,f.useState)({}),[m,u]=(0,f.useState)([]),[h,x]=(0,f.useState)(!1),[p,g]=(0,f.useState)(!1),[j,v]=(0,f.useState)(null),[y,b]=(0,f.useState)(!1),[N,w]=(0,f.useState)(null);(0,f.useRef)(null),(0,f.useEffect)(()=>{l&&(null==t?void 0:t.data)&&(async()=>{let e={};t.data.forEach(l=>{e[l.model_name]={status:"none",lastCheck:"None",lastSuccess:"None",loading:!1,error:void 0,fullError:void 0,successResponse:void 0}});try{let s=await (0,a.latestHealthChecksCall)(l);s&&s.latest_health_checks&&"object"==typeof s.latest_health_checks&&Object.entries(s.latest_health_checks).forEach(l=>{let[s,a]=l;if(!a)return;let r=null,i=t.data.find(e=>e.model_name===s);if(i)r=i.model_name;else{let e=t.data.find(e=>e.model_info&&e.model_info.id===s);if(e)r=e.model_name;else if(a.model_name){let e=t.data.find(e=>e.model_name===a.model_name);e&&(r=e.model_name)}}if(r){let l=a.error_message||void 0;e[r]={status:a.status||"unknown",lastCheck:a.checked_at?new Date(a.checked_at).toLocaleString():"None",lastSuccess:"healthy"===a.status&&a.checked_at?new Date(a.checked_at).toLocaleString():"None",loading:!1,error:l?Z(l):void 0,fullError:l,successResponse:"healthy"===a.status?a:void 0}}})}catch(e){console.warn("Failed to load health check history (using default states):",e)}c(e)})()},[l,t]);let Z=e=>{var l;if(!e)return"Health check failed";let t="string"==typeof e?e:JSON.stringify(e),s=t.match(/(\w+Error):\s*(\d{3})/i);if(s)return"".concat(s[1],": ").concat(s[2]);let a=t.match(/(AuthenticationError|RateLimitError|BadRequestError|InternalServerError|TimeoutError|NotFoundError|ForbiddenError|ServiceUnavailableError|BadGatewayError|ContentPolicyViolationError|\w+Error)/i),r=t.match(/\b(400|401|403|404|408|429|500|502|503|504)\b/);if(a&&r)return"".concat(a[1],": ").concat(r[1]);if(r){let e=r[1];return"".concat({400:"BadRequestError",401:"AuthenticationError",403:"ForbiddenError",404:"NotFoundError",408:"TimeoutError",429:"RateLimitError",500:"InternalServerError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError"}[e],": ").concat(e)}if(a){let e=a[1],l={AuthenticationError:"401",RateLimitError:"429",BadRequestError:"400",InternalServerError:"500",TimeoutError:"408",NotFoundError:"404",ForbiddenError:"403",ServiceUnavailableError:"503",BadGatewayError:"502",GatewayTimeoutError:"504",ContentPolicyViolationError:"400"}[e];return l?"".concat(e,": ").concat(l):e}for(let{pattern:e,replacement:l}of lz)if(e.test(t))return l;if(/missing.*api.*key|invalid.*key|unauthorized/i.test(t))return"AuthenticationError: 401";if(/rate.*limit|too.*many.*requests/i.test(t))return"RateLimitError: 429";if(/timeout|timed.*out/i.test(t))return"TimeoutError: 408";if(/not.*found/i.test(t))return"NotFoundError: 404";if(/forbidden|access.*denied/i.test(t))return"ForbiddenError: 403";if(/internal.*server.*error/i.test(t))return"InternalServerError: 500";let i=t.replace(/[\n\r]+/g," ").replace(/\s+/g," ").trim(),n=null===(l=i.split(/[.!?]/)[0])||void 0===l?void 0:l.trim();return n&&n.length>0?n.length>100?n.substring(0,97)+"...":n:i.length>100?i.substring(0,97)+"...":i},C=async e=>{if(l){c(l=>({...l,[e]:{...l[e],loading:!0,status:"checking"}}));try{var s,r;let i=await (0,a.individualModelHealthCheckCall)(l,e),n=new Date().toLocaleString();if(i.unhealthy_count>0&&i.unhealthy_endpoints&&i.unhealthy_endpoints.length>0){let l=(null===(s=i.unhealthy_endpoints[0])||void 0===s?void 0:s.error)||"Health check failed",t=Z(l);c(s=>{var a;return{...s,[e]:{status:"unhealthy",lastCheck:n,lastSuccess:(null===(a=s[e])||void 0===a?void 0:a.lastSuccess)||"None",loading:!1,error:t,fullError:l}}})}else c(l=>({...l,[e]:{status:"healthy",lastCheck:n,lastSuccess:n,loading:!1,successResponse:i}}));try{let s=await (0,a.latestHealthChecksCall)(l),i=t.data.find(l=>l.model_name===e);if(i){let l=i.model_info.id,t=null===(r=s.latest_health_checks)||void 0===r?void 0:r[l];if(t){let l=t.error_message||void 0;c(s=>{var a,r,i,n,o,d,c;return{...s,[e]:{status:t.status||(null===(a=s[e])||void 0===a?void 0:a.status)||"unknown",lastCheck:t.checked_at?new Date(t.checked_at).toLocaleString():(null===(r=s[e])||void 0===r?void 0:r.lastCheck)||"None",lastSuccess:"healthy"===t.status?t.checked_at?new Date(t.checked_at).toLocaleString():(null===(i=s[e])||void 0===i?void 0:i.lastSuccess)||"None":(null===(n=s[e])||void 0===n?void 0:n.lastSuccess)||"None",loading:!1,error:l?Z(l):null===(o=s[e])||void 0===o?void 0:o.error,fullError:l||(null===(d=s[e])||void 0===d?void 0:d.fullError),successResponse:"healthy"===t.status?t:null===(c=s[e])||void 0===c?void 0:c.successResponse}}})}}}catch(e){console.debug("Could not fetch updated status from database (non-critical):",e)}}catch(a){let l=new Date().toLocaleString(),t=a instanceof Error?a.message:String(a),s=Z(t);c(a=>{var r;return{...a,[e]:{status:"unhealthy",lastCheck:l,lastSuccess:(null===(r=a[e])||void 0===r?void 0:r.lastSuccess)||"None",loading:!1,error:s,fullError:t}}})}}},k=async()=>{let e=m.length>0?m:r,s=e.reduce((e,l)=>(e[l]={...d[l],loading:!0,status:"checking"},e),{});c(e=>({...e,...s}));let i={},n=e.map(async e=>{if(l)try{let s=await (0,a.individualModelHealthCheckCall)(l,e);i[e]=s;let r=new Date().toLocaleString();if(s.unhealthy_count>0&&s.unhealthy_endpoints&&s.unhealthy_endpoints.length>0){var t;let l=(null===(t=s.unhealthy_endpoints[0])||void 0===t?void 0:t.error)||"Health check failed",a=Z(l);c(t=>{var s;return{...t,[e]:{status:"unhealthy",lastCheck:r,lastSuccess:(null===(s=t[e])||void 0===s?void 0:s.lastSuccess)||"None",loading:!1,error:a,fullError:l}}})}else c(l=>({...l,[e]:{status:"healthy",lastCheck:r,lastSuccess:r,loading:!1,successResponse:s}}))}catch(a){console.error("Health check failed for ".concat(e,":"),a);let l=new Date().toLocaleString(),t=a instanceof Error?a.message:String(a),s=Z(t);c(a=>{var r;return{...a,[e]:{status:"unhealthy",lastCheck:l,lastSuccess:(null===(r=a[e])||void 0===r?void 0:r.lastSuccess)||"None",loading:!1,error:s,fullError:t}}})}});await Promise.allSettled(n);try{if(!l)return;let s=await (0,a.latestHealthChecksCall)(l);s.latest_health_checks&&Object.entries(s.latest_health_checks).forEach(l=>{let[s,a]=l,r=t.data.find(e=>e.model_info.id===s);if(r&&e.includes(r.model_name)&&a){let e=r.model_name,l=a.error_message||void 0;c(t=>{let s=t[e];return{...t,[e]:{status:a.status||(null==s?void 0:s.status)||"unknown",lastCheck:a.checked_at?new Date(a.checked_at).toLocaleString():(null==s?void 0:s.lastCheck)||"None",lastSuccess:"healthy"===a.status&&a.checked_at?new Date(a.checked_at).toLocaleString():(null==s?void 0:s.lastSuccess)||"None",loading:!1,error:l?Z(l):null==s?void 0:s.error,fullError:l||(null==s?void 0:s.fullError),successResponse:"healthy"===a.status?a:null==s?void 0:s.successResponse}}})}})}catch(e){console.warn("Failed to fetch updated health statuses from database (non-critical):",e)}},S=e=>{x(e),e?u(r):u([])},E=()=>{g(!1),v(null)},M=()=>{b(!1),w(null)};return(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"mb-6",children:(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(Q.Z,{children:"Model Health Status"}),(0,s.jsx)(H.Z,{className:"text-gray-600 mt-1",children:"Run health checks on individual models to verify they are working correctly"})]}),(0,s.jsxs)("div",{className:"flex items-center gap-3",children:[m.length>0&&(0,s.jsx)(A.Z,{size:"sm",variant:"light",onClick:()=>S(!1),className:"px-3 py-1 text-sm",children:"Clear Selection"}),(0,s.jsx)(A.Z,{size:"sm",variant:"secondary",onClick:k,disabled:Object.values(d).some(e=>e.loading),className:"px-3 py-1 text-sm",children:m.length>0&&m.length{l?u(l=>[...l,e]):(u(l=>l.filter(l=>l!==e)),x(!1))},S,C,e=>{switch(e){case"healthy":return(0,s.jsx)(P.Z,{color:"emerald",children:"healthy"});case"unhealthy":return(0,s.jsx)(P.Z,{color:"red",children:"unhealthy"});case"checking":return(0,s.jsx)(P.Z,{color:"blue",children:"checking"});case"none":return(0,s.jsx)(P.Z,{color:"gray",children:"none"});default:return(0,s.jsx)(P.Z,{color:"gray",children:"unknown"})}},i,(e,l,t)=>{v({modelName:e,cleanedError:l,fullError:t}),g(!0)},(e,l)=>{w({modelName:e,response:l}),b(!0)},n,o),data:t.data.map(e=>{let l=d[e.model_name]||{status:"none",lastCheck:"None",loading:!1};return{model_name:e.model_name,model_info:e.model_info,provider:e.provider,litellm_model_name:e.litellm_model_name,health_status:l.status,last_check:l.lastCheck,last_success:l.lastSuccess||"None",health_loading:l.loading,health_error:l.error,health_full_error:l.fullError}}),isLoading:!1})}),(0,s.jsx)(ei.Z,{title:j?"Health Check Error - ".concat(j.modelName):"Error Details",open:p,onCancel:E,footer:[(0,s.jsx)(_.ZP,{onClick:E,children:"Close"},"close")],width:800,children:j&&(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Error:"}),(0,s.jsx)("div",{className:"mt-2 p-3 bg-red-50 border border-red-200 rounded-md",children:(0,s.jsx)(H.Z,{className:"text-red-800",children:j.cleanedError})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Full Error Details:"}),(0,s.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md max-h-96 overflow-y-auto",children:(0,s.jsx)("pre",{className:"text-sm text-gray-800 whitespace-pre-wrap",children:j.fullError})})]})]})}),(0,s.jsx)(ei.Z,{title:N?"Health Check Response - ".concat(N.modelName):"Response Details",open:y,onCancel:M,footer:[(0,s.jsx)(_.ZP,{onClick:M,children:"Close"},"close")],width:800,children:N&&(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Status:"}),(0,s.jsx)("div",{className:"mt-2 p-3 bg-green-50 border border-green-200 rounded-md",children:(0,s.jsx)(H.Z,{className:"text-green-800",children:"Health check passed successfully"})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Response Details:"}),(0,s.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md max-h-96 overflow-y-auto",children:(0,s.jsx)("pre",{className:"text-sm text-gray-800 whitespace-pre-wrap",children:JSON.stringify(N.response,null,2)})})]})]})})]})},lV=t(47686),lq=t(77355),lD=t(93416),lB=t(95704),lG=e=>{let{accessToken:l,initialModelGroupAlias:t={},onAliasUpdate:r}=e,[i,n]=(0,f.useState)([]),[o,d]=(0,f.useState)({aliasName:"",targetModelGroup:""}),[c,m]=(0,f.useState)(null),[u,h]=(0,f.useState)(!0);(0,f.useEffect)(()=>{n(Object.entries(t).map((e,l)=>{var t;let[s,a]=e;return{id:"".concat(l,"-").concat(s),aliasName:s,targetModelGroup:"string"==typeof a?a:null!==(t=null==a?void 0:a.model)&&void 0!==t?t:""}}))},[t]);let x=async e=>{if(!l)return console.error("Access token is missing"),!1;try{let t={};return e.forEach(e=>{t[e.aliasName]=e.targetModelGroup}),console.log("Saving model group alias:",t),await (0,a.setCallbacksCall)(l,{router_settings:{model_group_alias:t}}),r&&r(t),!0}catch(e){return console.error("Failed to save model group alias settings:",e),ec.ZP.fromBackend("Failed to save model group alias settings"),!1}},p=async()=>{if(!o.aliasName||!o.targetModelGroup){ec.ZP.fromBackend("Please provide both alias name and target model group");return}if(i.some(e=>e.aliasName===o.aliasName)){ec.ZP.fromBackend("An alias with this name already exists");return}let e=[...i,{id:"".concat(Date.now(),"-").concat(o.aliasName),aliasName:o.aliasName,targetModelGroup:o.targetModelGroup}];await x(e)&&(n(e),d({aliasName:"",targetModelGroup:""}),ec.ZP.success("Alias added successfully"))},g=e=>{m({...e})},j=async()=>{if(!c)return;if(!c.aliasName||!c.targetModelGroup){ec.ZP.fromBackend("Please provide both alias name and target model group");return}if(i.some(e=>e.id!==c.id&&e.aliasName===c.aliasName)){ec.ZP.fromBackend("An alias with this name already exists");return}let e=i.map(e=>e.id===c.id?c:e);await x(e)&&(n(e),m(null),ec.ZP.success("Alias updated successfully"))},v=()=>{m(null)},_=async e=>{let l=i.filter(l=>l.id!==e);await x(l)&&(n(l),ec.ZP.success("Alias deleted successfully"))},y=i.reduce((e,l)=>(e[l.aliasName]=l.targetModelGroup,e),{});return(0,s.jsxs)(lB.Zb,{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between cursor-pointer",onClick:()=>h(!u),children:[(0,s.jsxs)("div",{className:"flex flex-col",children:[(0,s.jsx)(lB.Dx,{className:"mb-0",children:"Model Group Alias Settings"}),(0,s.jsx)("p",{className:"text-sm text-gray-500",children:"Create aliases for your model groups to simplify API calls. For example, you can create an alias 'gpt-4o' that points to 'gpt-4o-mini-openai' model group."})]}),(0,s.jsx)("div",{className:"flex items-center",children:u?(0,s.jsx)(b.Z,{className:"w-5 h-5 text-gray-500"}):(0,s.jsx)(lV.Z,{className:"w-5 h-5 text-gray-500"})})]}),u&&(0,s.jsxs)("div",{className:"mt-4",children:[(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsx)(lB.xv,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,s.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,s.jsx)("input",{type:"text",value:o.aliasName,onChange:e=>d({...o,aliasName:e.target.value}),placeholder:"e.g., gpt-4o",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model Group"}),(0,s.jsx)("input",{type:"text",value:o.targetModelGroup,onChange:e=>d({...o,targetModelGroup:e.target.value}),placeholder:"e.g., gpt-4o-mini-openai",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]}),(0,s.jsx)("div",{className:"flex items-end",children:(0,s.jsxs)("button",{onClick:p,disabled:!o.aliasName||!o.targetModelGroup,className:"flex items-center px-4 py-2 rounded-md text-sm ".concat(o.aliasName&&o.targetModelGroup?"bg-green-600 text-white hover:bg-green-700":"bg-gray-300 text-gray-500 cursor-not-allowed"),children:[(0,s.jsx)(lq.Z,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,s.jsx)(lB.xv,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,s.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,s.jsx)("div",{className:"overflow-x-auto",children:(0,s.jsxs)(lB.iA,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,s.jsx)(lB.ss,{children:(0,s.jsxs)(lB.SC,{children:[(0,s.jsx)(lB.xs,{className:"py-1 h-8",children:"Alias Name"}),(0,s.jsx)(lB.xs,{className:"py-1 h-8",children:"Target Model Group"}),(0,s.jsx)(lB.xs,{className:"py-1 h-8",children:"Actions"})]})}),(0,s.jsxs)(lB.RM,{children:[i.map(e=>(0,s.jsx)(lB.SC,{className:"h-8",children:c&&c.id===e.id?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(lB.pj,{className:"py-0.5",children:(0,s.jsx)("input",{type:"text",value:c.aliasName,onChange:e=>m({...c,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,s.jsx)(lB.pj,{className:"py-0.5",children:(0,s.jsx)("input",{type:"text",value:c.targetModelGroup,onChange:e=>m({...c,targetModelGroup:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,s.jsx)(lB.pj,{className:"py-0.5 whitespace-nowrap",children:(0,s.jsxs)("div",{className:"flex space-x-2",children:[(0,s.jsx)("button",{onClick:j,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,s.jsx)("button",{onClick:v,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(lB.pj,{className:"py-0.5 text-sm text-gray-900",children:e.aliasName}),(0,s.jsx)(lB.pj,{className:"py-0.5 text-sm text-gray-500",children:e.targetModelGroup}),(0,s.jsx)(lB.pj,{className:"py-0.5 whitespace-nowrap",children:(0,s.jsxs)("div",{className:"flex space-x-2",children:[(0,s.jsx)("button",{onClick:()=>g(e),className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,s.jsx)(lD.Z,{className:"w-3 h-3"})}),(0,s.jsx)("button",{onClick:()=>_(e.id),className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,s.jsx)(S.Z,{className:"w-3 h-3"})})]})})]})},e.id)),0===i.length&&(0,s.jsx)(lB.SC,{children:(0,s.jsx)(lB.pj,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),(0,s.jsxs)(lB.Zb,{children:[(0,s.jsx)(lB.Dx,{className:"mb-4",children:"Configuration Example"}),(0,s.jsx)(lB.xv,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config.yaml:"}),(0,s.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,s.jsxs)("div",{className:"text-gray-700",children:["router_settings:",(0,s.jsx)("br",{}),"\xa0\xa0model_group_alias:",0===Object.keys(y).length?(0,s.jsxs)("span",{className:"text-gray-500",children:[(0,s.jsx)("br",{}),"\xa0\xa0\xa0\xa0# No aliases configured yet"]}):Object.entries(y).map(e=>{let[l,t]=e;return(0,s.jsxs)("span",{children:[(0,s.jsx)("br",{}),'\xa0\xa0\xa0\xa0"',l,'": "',t,'"']},l)})]})})]})]})]})},lU=t(10900),lH=t(12514),lK=t(49566),lJ=t(30401),lW=t(78867),lY=t(59872),l$=e=>{let{isVisible:l,onCancel:t,onSuccess:r,modelData:i,accessToken:n,userRole:o}=e,[d]=ev.Z.useForm(),[c,m]=(0,f.useState)(!1),[u,h]=(0,f.useState)([]),[x,p]=(0,f.useState)([]),[g,j]=(0,f.useState)(!1),[v,y]=(0,f.useState)(!1),[b,N]=(0,f.useState)(null);(0,f.useEffect)(()=>{l&&i&&w()},[l,i]),(0,f.useEffect)(()=>{let e=async()=>{if(n)try{let e=await (0,a.modelAvailableCall)(n,"","",!1,null,!0,!0);h(e.data.map(e=>e.id))}catch(e){console.error("Error fetching model access groups:",e)}},t=async()=>{if(n)try{let e=await (0,e5.p)(n);p(e)}catch(e){console.error("Error fetching model info:",e)}};l&&(e(),t())},[l,n]);let w=()=>{try{var e,l,t,s,a,r;let n=null;(null===(e=i.litellm_params)||void 0===e?void 0:e.auto_router_config)&&(n="string"==typeof i.litellm_params.auto_router_config?JSON.parse(i.litellm_params.auto_router_config):i.litellm_params.auto_router_config),N(n),d.setFieldsValue({auto_router_name:i.model_name,auto_router_default_model:(null===(l=i.litellm_params)||void 0===l?void 0:l.auto_router_default_model)||"",auto_router_embedding_model:(null===(t=i.litellm_params)||void 0===t?void 0:t.auto_router_embedding_model)||"",model_access_group:(null===(s=i.model_info)||void 0===s?void 0:s.access_groups)||[]});let o=new Set(x.map(e=>e.model_group));j(!o.has(null===(a=i.litellm_params)||void 0===a?void 0:a.auto_router_default_model)),y(!o.has(null===(r=i.litellm_params)||void 0===r?void 0:r.auto_router_embedding_model))}catch(e){console.error("Error parsing auto router config:",e),ec.ZP.fromBackend("Error loading auto router configuration")}},Z=async()=>{try{m(!0);let e=await d.validateFields(),l={...i.litellm_params,auto_router_config:JSON.stringify(b),auto_router_default_model:e.auto_router_default_model,auto_router_embedding_model:e.auto_router_embedding_model||void 0},s={...i.model_info,access_groups:e.model_access_group||[]},o={model_name:e.auto_router_name,litellm_params:l,model_info:s};await (0,a.modelPatchUpdateCall)(n,o,i.model_info.id);let c={...i,model_name:e.auto_router_name,litellm_params:l,model_info:s};ec.ZP.success("Auto router configuration updated successfully"),r(c),t()}catch(e){console.error("Error updating auto router:",e),ec.ZP.fromBackend("Failed to update auto router configuration")}finally{m(!1)}},C=x.map(e=>({value:e.model_group,label:e.model_group}));return(0,s.jsx)(ei.Z,{title:"Edit Auto Router Configuration",open:l,onCancel:t,footer:[(0,s.jsx)(_.ZP,{onClick:t,children:"Cancel"},"cancel"),(0,s.jsx)(_.ZP,{loading:c,onClick:Z,children:"Save Changes"},"submit")],width:1e3,destroyOnHidden:!0,children:(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsx)(eC.x,{className:"text-gray-600",children:"Edit the auto router configuration including routing logic, default models, and access settings."}),(0,s.jsxs)(ev.Z,{form:d,layout:"vertical",className:"space-y-4",children:[(0,s.jsx)(ev.Z.Item,{label:"Auto Router Name",name:"auto_router_name",rules:[{required:!0,message:"Auto router name is required"}],children:(0,s.jsx)(eC.o,{placeholder:"e.g., auto_router_1, smart_routing"})}),(0,s.jsx)("div",{className:"w-full",children:(0,s.jsx)(lt,{modelInfo:x,value:b,onChange:e=>{N(e)}})}),(0,s.jsx)(ev.Z.Item,{label:"Default Model",name:"auto_router_default_model",rules:[{required:!0,message:"Default model is required"}],children:(0,s.jsx)(eb.default,{placeholder:"Select a default model",onChange:e=>{j("custom"===e)},options:[...C,{value:"custom",label:"Enter custom model name"}],showSearch:!0})}),(0,s.jsx)(ev.Z.Item,{label:"Embedding Model",name:"auto_router_embedding_model",children:(0,s.jsx)(eb.default,{placeholder:"Select an embedding model (optional)",onChange:e=>{y("custom"===e)},options:[...C,{value:"custom",label:"Enter custom model name"}],showSearch:!0,allowClear:!0})}),"Admin"===o&&(0,s.jsx)(ev.Z.Item,{label:"Model Access Groups",name:"model_access_group",tooltip:"Control who can access this auto router",children:(0,s.jsx)(eb.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],options:u.map(e=>({value:e,label:e})),maxTagCount:"responsive",allowClear:!0})})]})]})})};let{Title:lX,Link:lQ}=M.default;var l0=e=>{let{isVisible:l,onCancel:t,onAddCredential:a,existingCredential:r,setIsCredentialModalOpen:i}=e,[n]=ev.Z.useForm();return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(r))),(0,s.jsx)(ei.Z,{title:"Reuse Credentials",open:l,onCancel:()=>{t(),n.resetFields()},footer:null,width:600,children:(0,s.jsxs)(ev.Z,{form:n,onFinish:e=>{a(e),n.resetFields(),i(!1)},layout:"vertical",children:[(0,s.jsx)(ev.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==r?void 0:r.credential_name,children:(0,s.jsx)(ey.o,{placeholder:"Enter a friendly name for these credentials"})}),Object.entries((null==r?void 0:r.credential_values)||{}).map(e=>{let[l,t]=e;return(0,s.jsx)(ev.Z.Item,{label:l,name:l,initialValue:t,children:(0,s.jsx)(ey.o,{placeholder:"Enter ".concat(l),disabled:!0})},l)}),(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(L.Z,{title:"Get help on our github",children:(0,s.jsx)(lQ,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(_.ZP,{onClick:()=>{t(),n.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,s.jsx)(_.ZP,{htmlType:"submit",children:"Reuse Credentials"})]})]})]})})};function l1(e){var l,t,r,i,n,o,d,c,h,x,p,g,j,v,y,b,N,w,Z,C,P,E,M,F,I,T,R,z,O,B,G,K,J;let{modelId:W,onClose:Y,accessToken:X,userID:ee,userRole:el,onModelUpdate:et,modelAccessGroups:es}=e,[ea]=ev.Z.useForm(),[er,en]=(0,f.useState)(null),[eo,ed]=(0,f.useState)(!1),[em,eu]=(0,f.useState)(!1),[eh,ep]=(0,f.useState)(!1),[eg,ef]=(0,f.useState)(!1),[ej,ey]=(0,f.useState)(!1),[eN,ew]=(0,f.useState)(!1),[eZ,eC]=(0,f.useState)(null),[ek,eS]=(0,f.useState)(!1),[eP,eE]=(0,f.useState)({}),[eM,eL]=(0,f.useState)(!1),[eF,eI]=(0,f.useState)([]),[eT,eR]=(0,f.useState)({}),{data:ez,isLoading:eO}=(0,u.XP)(1,50,void 0,W),{data:eV}=m(),{data:eD}=(0,u.VI)(),eB=e=>null!=eV&&"object"==typeof eV&&e in eV?eV[e].litellm_provider:"openai",eJ=(0,f.useMemo)(()=>(null==ez?void 0:ez.data)&&0!==ez.data.length&&$(ez,eB).data[0]||null,[ez,eV]),eW=("Admin"===el||(null==eJ?void 0:null===(l=eJ.model_info)||void 0===l?void 0:l.created_by)===ee)&&(null==eJ?void 0:null===(t=eJ.model_info)||void 0===t?void 0:t.db_model),eY="Admin"===el,e$=(null==eJ?void 0:null===(r=eJ.litellm_params)||void 0===r?void 0:r.auto_router_config)!=null,eX=(null==eJ?void 0:null===(i=eJ.litellm_params)||void 0===i?void 0:i.litellm_credential_name)!=null&&(null==eJ?void 0:null===(n=eJ.litellm_params)||void 0===n?void 0:n.litellm_credential_name)!=void 0;(0,f.useEffect)(()=>{if(eJ&&!er){var e,l,t,s,a,r,i;let n=eJ;n.litellm_model_name||(n={...n,litellm_model_name:null!==(i=null!==(r=null!==(a=null==n?void 0:null===(l=n.litellm_params)||void 0===l?void 0:l.litellm_model_name)&&void 0!==a?a:null==n?void 0:null===(t=n.litellm_params)||void 0===t?void 0:t.model)&&void 0!==r?r:null==n?void 0:null===(s=n.model_info)||void 0===s?void 0:s.key)&&void 0!==i?i:null}),en(n),(null==n?void 0:null===(e=n.litellm_params)||void 0===e?void 0:e.cache_control_injection_points)&&eS(!0)}},[eJ,er]),(0,f.useEffect)(()=>{let e=async()=>{var e,l,t,s,r,i,n;if(!X||eJ)return;let o=(await (0,a.modelInfoV1Call)(X,W)).data[0];o&&!o.litellm_model_name&&(o={...o,litellm_model_name:null!==(n=null!==(i=null!==(r=null==o?void 0:null===(l=o.litellm_params)||void 0===l?void 0:l.litellm_model_name)&&void 0!==r?r:null==o?void 0:null===(t=o.litellm_params)||void 0===t?void 0:t.model)&&void 0!==i?i:null==o?void 0:null===(s=o.model_info)||void 0===s?void 0:s.key)&&void 0!==n?n:null}),en(o),(null==o?void 0:null===(e=o.litellm_params)||void 0===e?void 0:e.cache_control_injection_points)&&eS(!0)},l=async()=>{if(X)try{let e=(await (0,a.getGuardrailsList)(X)).guardrails.map(e=>e.guardrail_name);eI(e)}catch(e){console.error("Failed to fetch guardrails:",e)}},t=async()=>{if(X)try{let e=await (0,a.tagListCall)(X);eR(e)}catch(e){console.error("Failed to fetch tags:",e)}};(async()=>{if(!X||eX)return;let e=await (0,a.credentialGetCall)(X,null,W);eC({credential_name:e.credential_name,credential_values:e.credential_values,credential_info:e.credential_info})})(),e(),l(),t()},[X,W]);let eQ=async e=>{var l;if(!X)return;let t={credential_name:e.credential_name,model_id:W,credential_info:{custom_llm_provider:null===(l=er.litellm_params)||void 0===l?void 0:l.custom_llm_provider}};ec.ZP.info("Storing credential.."),await (0,a.credentialCreateCall)(X,t),ec.ZP.success("Credential stored successfully")},e0=async e=>{try{var l;let t;if(!X)return;ey(!0);let s={};try{s=e.litellm_extra_params?JSON.parse(e.litellm_extra_params):{}}catch(e){ec.ZP.fromBackend("Invalid JSON in LiteLLM Params"),ey(!1);return}let r={...e.litellm_params,...s,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,tags:e.tags};e.guardrails&&(r.guardrails=e.guardrails),e.cache_control&&(null===(l=e.cache_control_injection_points)||void 0===l?void 0:l.length)>0?r.cache_control_injection_points=e.cache_control_injection_points:delete r.cache_control_injection_points;try{t=e.model_info?JSON.parse(e.model_info):eJ.model_info,e.model_access_group&&(t={...t,access_groups:e.model_access_group}),void 0!==e.health_check_model&&(t={...t,health_check_model:e.health_check_model})}catch(e){ec.ZP.fromBackend("Invalid JSON in Model Info");return}let i={model_name:e.model_name,litellm_params:r,model_info:t};await (0,a.modelPatchUpdateCall)(X,i,W);let n={...er,model_name:e.model_name,litellm_model_name:e.litellm_model_name,litellm_params:r,model_info:t};en(n),et&&et(n),ec.ZP.success("Model settings updated successfully"),ef(!1),ew(!1)}catch(e){console.error("Error updating model:",e),ec.ZP.fromBackend("Failed to update model settings")}finally{ey(!1)}};if(eO)return(0,s.jsxs)("div",{className:"p-4",children:[(0,s.jsx)(A.Z,{icon:lU.Z,variant:"light",onClick:Y,className:"mb-4",children:"Back to Models"}),(0,s.jsx)(H.Z,{children:"Loading..."})]});if(!eJ)return(0,s.jsxs)("div",{className:"p-4",children:[(0,s.jsx)(A.Z,{icon:lU.Z,variant:"light",onClick:Y,className:"mb-4",children:"Back to Models"}),(0,s.jsx)(H.Z,{children:"Model not found"})]});let e1=async()=>{if(X)try{var e,l,t;ec.ZP.info("Testing connection...");let s=await (0,a.testConnectionRequest)(X,{custom_llm_provider:er.litellm_params.custom_llm_provider,litellm_credential_name:er.litellm_params.litellm_credential_name,model:er.litellm_model_name},{mode:null===(e=er.model_info)||void 0===e?void 0:e.mode},null===(l=er.model_info)||void 0===l?void 0:l.mode);if("success"===s.status)ec.ZP.success("Connection test successful!");else throw Error((null==s?void 0:null===(t=s.result)||void 0===t?void 0:t.error)||(null==s?void 0:s.message)||"Unknown error")}catch(e){e instanceof Error?ec.ZP.error("Error testing connection: "+(0,l_.aS)(e.message,100)):ec.ZP.error("Error testing connection: "+String(e))}},e2=async()=>{try{if(eu(!0),!X)return;await (0,a.modelDeleteCall)(X,W),ec.ZP.success("Model deleted successfully"),et&&et({deleted:!0,model_info:{id:W}}),Y()}catch(e){console.error("Error deleting the model:",e),ec.ZP.fromBackend("Failed to delete model")}finally{eu(!1),ed(!1)}},e4=async(e,l)=>{await (0,lY.vQ)(e)&&(eE(e=>({...e,[l]:!0})),setTimeout(()=>{eE(e=>({...e,[l]:!1}))},2e3))},e5=eJ.litellm_model_name.includes("*");return(0,s.jsxs)("div",{className:"p-4",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(A.Z,{icon:lU.Z,variant:"light",onClick:Y,className:"mb-4",children:"Back to Models"}),(0,s.jsxs)(Q.Z,{children:["Public Model Name: ",V(eJ)]}),(0,s.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,s.jsx)(H.Z,{className:"text-gray-500 font-mono",children:eJ.model_info.id}),(0,s.jsx)(_.ZP,{type:"text",size:"small",icon:eP["model-id"]?(0,s.jsx)(lJ.Z,{size:12}):(0,s.jsx)(lW.Z,{size:12}),onClick:()=>e4(eJ.model_info.id,"model-id"),className:"left-2 z-10 transition-all duration-200 ".concat(eP["model-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100")})]})]}),(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)(A.Z,{variant:"secondary",icon:eq.Z,onClick:e1,className:"flex items-center gap-2","data-testid":"test-connection-button",children:"Test Connection"}),(0,s.jsx)(A.Z,{icon:k.Z,variant:"secondary",onClick:()=>ep(!0),className:"flex items-center",disabled:!eY,"data-testid":"reuse-credentials-button",children:"Re-use Credentials"}),(0,s.jsx)(A.Z,{icon:S.Z,variant:"secondary",onClick:()=>ed(!0),className:"flex items-center text-red-500 border-red-500 hover:text-red-700",disabled:!eW,"data-testid":"delete-model-button",children:"Delete Model"})]})]}),(0,s.jsxs)(eU.Z,{children:[(0,s.jsxs)(eH.Z,{className:"mb-6",children:[(0,s.jsx)(eG.Z,{children:"Overview"}),(0,s.jsx)(eG.Z,{children:"Raw JSON"})]}),(0,s.jsxs)(eK.Z,{children:[(0,s.jsxs)(U.Z,{children:[(0,s.jsxs)(D.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6 mb-6",children:[(0,s.jsxs)(lH.Z,{children:[(0,s.jsx)(H.Z,{children:"Provider"}),(0,s.jsxs)("div",{className:"mt-2 flex items-center space-x-2",children:[eJ.provider&&(0,s.jsx)("img",{src:(0,ex.dr)(eJ.provider).logo,alt:"".concat(eJ.provider," logo"),className:"w-4 h-4",onError:e=>{let l=e.currentTarget,t=l.parentElement;if(t&&t.contains(l))try{var s;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===(s=eJ.provider)||void 0===s?void 0:s.charAt(0))||"-",t.replaceChild(e,l)}catch(e){console.error("Failed to replace provider logo fallback:",e)}}}),(0,s.jsx)(Q.Z,{children:eJ.provider||"Not Set"})]})]}),(0,s.jsxs)(lH.Z,{children:[(0,s.jsx)(H.Z,{children:"LiteLLM Model"}),(0,s.jsx)("div",{className:"mt-2 overflow-hidden",children:(0,s.jsx)(L.Z,{title:eJ.litellm_model_name||"Not Set",children:(0,s.jsx)("div",{className:"break-all text-sm font-medium leading-relaxed cursor-pointer",children:eJ.litellm_model_name||"Not Set"})})})]}),(0,s.jsxs)(lH.Z,{children:[(0,s.jsx)(H.Z,{children:"Pricing"}),(0,s.jsxs)("div",{className:"mt-2",children:[(0,s.jsxs)(H.Z,{children:["Input: $",eJ.input_cost,"/1M tokens"]}),(0,s.jsxs)(H.Z,{children:["Output: $",eJ.output_cost,"/1M tokens"]})]})]})]}),(0,s.jsxs)("div",{className:"mb-6 text-sm text-gray-500 flex items-center gap-x-6",children:[(0,s.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,s.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,s.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"," ",eJ.model_info.created_at?new Date(eJ.model_info.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Not Set"]}),(0,s.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,s.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,s.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 ",eJ.model_info.created_by||"Not Set"]})]}),(0,s.jsxs)(lH.Z,{children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,s.jsx)(Q.Z,{children:"Model Settings"}),(0,s.jsxs)("div",{className:"flex gap-2",children:[e$&&eW&&!eN&&(0,s.jsx)(A.Z,{onClick:()=>eL(!0),className:"flex items-center",children:"Edit Auto Router"}),eW?!eN&&(0,s.jsx)(A.Z,{onClick:()=>ew(!0),className:"flex items-center",children:"Edit Settings"}):(0,s.jsx)(L.Z,{title:"Only DB models can be edited. You must be an admin or the creator of the model to edit it.",children:(0,s.jsx)(q.Z,{})})]})]}),er?(0,s.jsx)(ev.Z,{form:ea,onFinish:e0,initialValues:{model_name:er.model_name,litellm_model_name:er.litellm_model_name,api_base:er.litellm_params.api_base,custom_llm_provider:er.litellm_params.custom_llm_provider,organization:er.litellm_params.organization,tpm:er.litellm_params.tpm,rpm:er.litellm_params.rpm,max_retries:er.litellm_params.max_retries,timeout:er.litellm_params.timeout,stream_timeout:er.litellm_params.stream_timeout,input_cost:er.litellm_params.input_cost_per_token?1e6*er.litellm_params.input_cost_per_token:(null===(o=er.model_info)||void 0===o?void 0:o.input_cost_per_token)*1e6||null,output_cost:(null===(d=er.litellm_params)||void 0===d?void 0:d.output_cost_per_token)?1e6*er.litellm_params.output_cost_per_token:(null===(c=er.model_info)||void 0===c?void 0:c.output_cost_per_token)*1e6||null,cache_control:null!==(h=er.litellm_params)&&void 0!==h&&!!h.cache_control_injection_points,cache_control_injection_points:(null===(x=er.litellm_params)||void 0===x?void 0:x.cache_control_injection_points)||[],model_access_group:Array.isArray(null===(p=er.model_info)||void 0===p?void 0:p.access_groups)?er.model_info.access_groups:[],guardrails:Array.isArray(null===(g=er.litellm_params)||void 0===g?void 0:g.guardrails)?er.litellm_params.guardrails:[],tags:Array.isArray(null===(j=er.litellm_params)||void 0===j?void 0:j.tags)?er.litellm_params.tags:[],health_check_model:e5?null===(v=er.model_info)||void 0===v?void 0:v.health_check_model:null,litellm_extra_params:JSON.stringify(er.litellm_params||{},null,2)},layout:"vertical",onValuesChange:()=>ef(!0),children:(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Model Name"}),eN?(0,s.jsx)(ev.Z.Item,{name:"model_name",className:"mb-0",children:(0,s.jsx)(lK.Z,{placeholder:"Enter model name"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:er.model_name})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"LiteLLM Model Name"}),eN?(0,s.jsx)(ev.Z.Item,{name:"litellm_model_name",className:"mb-0",children:(0,s.jsx)(lK.Z,{placeholder:"Enter LiteLLM model name"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:er.litellm_model_name})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Input Cost (per 1M tokens)"}),eN?(0,s.jsx)(ev.Z.Item,{name:"input_cost",className:"mb-0",children:(0,s.jsx)(lf.Z,{placeholder:"Enter input cost"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==er?void 0:null===(y=er.litellm_params)||void 0===y?void 0:y.input_cost_per_token)?((null===(b=er.litellm_params)||void 0===b?void 0:b.input_cost_per_token)*1e6).toFixed(4):(null==er?void 0:null===(N=er.model_info)||void 0===N?void 0:N.input_cost_per_token)?(1e6*er.model_info.input_cost_per_token).toFixed(4):"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Output Cost (per 1M tokens)"}),eN?(0,s.jsx)(ev.Z.Item,{name:"output_cost",className:"mb-0",children:(0,s.jsx)(lf.Z,{placeholder:"Enter output cost"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==er?void 0:null===(w=er.litellm_params)||void 0===w?void 0:w.output_cost_per_token)?(1e6*er.litellm_params.output_cost_per_token).toFixed(4):(null==er?void 0:null===(Z=er.model_info)||void 0===Z?void 0:Z.output_cost_per_token)?(1e6*er.model_info.output_cost_per_token).toFixed(4):"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"API Base"}),eN?(0,s.jsx)(ev.Z.Item,{name:"api_base",className:"mb-0",children:(0,s.jsx)(lK.Z,{placeholder:"Enter API base"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(C=er.litellm_params)||void 0===C?void 0:C.api_base)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Custom LLM Provider"}),eN?(0,s.jsx)(ev.Z.Item,{name:"custom_llm_provider",className:"mb-0",children:(0,s.jsx)(lK.Z,{placeholder:"Enter custom LLM provider"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(P=er.litellm_params)||void 0===P?void 0:P.custom_llm_provider)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Organization"}),eN?(0,s.jsx)(ev.Z.Item,{name:"organization",className:"mb-0",children:(0,s.jsx)(lK.Z,{placeholder:"Enter organization"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(E=er.litellm_params)||void 0===E?void 0:E.organization)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"TPM (Tokens per Minute)"}),eN?(0,s.jsx)(ev.Z.Item,{name:"tpm",className:"mb-0",children:(0,s.jsx)(lf.Z,{placeholder:"Enter TPM"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(M=er.litellm_params)||void 0===M?void 0:M.tpm)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"RPM (Requests per Minute)"}),eN?(0,s.jsx)(ev.Z.Item,{name:"rpm",className:"mb-0",children:(0,s.jsx)(lf.Z,{placeholder:"Enter RPM"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(F=er.litellm_params)||void 0===F?void 0:F.rpm)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Max Retries"}),eN?(0,s.jsx)(ev.Z.Item,{name:"max_retries",className:"mb-0",children:(0,s.jsx)(lf.Z,{placeholder:"Enter max retries"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(I=er.litellm_params)||void 0===I?void 0:I.max_retries)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Timeout (seconds)"}),eN?(0,s.jsx)(ev.Z.Item,{name:"timeout",className:"mb-0",children:(0,s.jsx)(lf.Z,{placeholder:"Enter timeout"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(T=er.litellm_params)||void 0===T?void 0:T.timeout)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Stream Timeout (seconds)"}),eN?(0,s.jsx)(ev.Z.Item,{name:"stream_timeout",className:"mb-0",children:(0,s.jsx)(lf.Z,{placeholder:"Enter stream timeout"})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(R=er.litellm_params)||void 0===R?void 0:R.stream_timeout)||"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Model Access Groups"}),eN?(0,s.jsx)(ev.Z.Item,{name:"model_access_group",className:"mb-0",children:(0,s.jsx)(eb.default,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],maxTagCount:"responsive",allowClear:!0,style:{width:"100%"},options:null==es?void 0:es.map(e=>({value:e,label:e}))})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(z=er.model_info)||void 0===z?void 0:z.access_groups)?Array.isArray(er.model_info.access_groups)?er.model_info.access_groups.length>0?(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:er.model_info.access_groups.map((e,l)=>(0,s.jsx)("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800",children:e},l))}):"No groups assigned":er.model_info.access_groups:"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsxs)(H.Z,{className:"font-medium",children:["Guardrails",(0,s.jsx)(L.Z,{title:"Apply safety guardrails to this model to filter content or enforce policies",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(q.Z,{style:{marginLeft:"4px"}})})})]}),eN?(0,s.jsx)(ev.Z.Item,{name:"guardrails",className:"mb-0",children:(0,s.jsx)(eb.default,{mode:"tags",showSearch:!0,placeholder:"Select existing guardrails or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],maxTagCount:"responsive",allowClear:!0,style:{width:"100%"},options:eF.map(e=>({value:e,label:e}))})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(O=er.litellm_params)||void 0===O?void 0:O.guardrails)?Array.isArray(er.litellm_params.guardrails)?er.litellm_params.guardrails.length>0?(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:er.litellm_params.guardrails.map((e,l)=>(0,s.jsx)("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800",children:e},l))}):"No guardrails assigned":er.litellm_params.guardrails:"Not Set"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Tags"}),eN?(0,s.jsx)(ev.Z.Item,{name:"tags",className:"mb-0",children:(0,s.jsx)(eb.default,{mode:"tags",showSearch:!0,placeholder:"Select existing tags or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],maxTagCount:"responsive",allowClear:!0,style:{width:"100%"},options:Object.values(eT).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(B=er.litellm_params)||void 0===B?void 0:B.tags)?Array.isArray(er.litellm_params.tags)?er.litellm_params.tags.length>0?(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:er.litellm_params.tags.map((e,l)=>(0,s.jsx)("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800",children:e},l))}):"No tags assigned":er.litellm_params.tags:"Not Set"})]}),e5&&(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Health Check Model"}),eN?(0,s.jsx)(ev.Z.Item,{name:"health_check_model",className:"mb-0",children:(0,s.jsx)(eb.default,{showSearch:!0,placeholder:"Select existing health check model",optionFilterProp:"children",allowClear:!0,options:(()=>{var e;let l=eJ.litellm_model_name.split("/")[0];return(null==eD?void 0:null===(e=eD.data)||void 0===e?void 0:e.filter(e=>{var t;return(null===(t=e.providers)||void 0===t?void 0:t.includes(l))&&e.model_group!==eJ.litellm_model_name}).map(e=>({value:e.model_group,label:e.model_group})))||[]})()})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(G=er.model_info)||void 0===G?void 0:G.health_check_model)||"Not Set"})]}),eN?(0,s.jsx)(lv,{form:ea,showCacheControl:ek,onCacheControlChange:e=>eS(e)}):(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Cache Control"}),(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(K=er.litellm_params)||void 0===K?void 0:K.cache_control_injection_points)?(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{children:"Enabled"}),(0,s.jsx)("div",{className:"mt-2",children:er.litellm_params.cache_control_injection_points.map((e,l)=>(0,s.jsxs)("div",{className:"text-sm text-gray-600 mb-1",children:["Location: ",e.location,",",e.role&&(0,s.jsxs)("span",{children:[" Role: ",e.role]}),void 0!==e.index&&(0,s.jsxs)("span",{children:[" Index: ",e.index]})]},l))})]}):"Disabled"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Model Info"}),eN?(0,s.jsx)(ev.Z.Item,{name:"model_info",className:"mb-0",children:(0,s.jsx)(eA.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}',defaultValue:JSON.stringify(eJ.model_info,null,2)})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(0,s.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(er.model_info,null,2)})})]}),(0,s.jsxs)("div",{children:[(0,s.jsxs)(H.Z,{className:"font-medium",children:["LiteLLM Params",(0,s.jsx)(L.Z,{title:"Optional litellm params used for making a litellm.completion() call. Some params are automatically added by LiteLLM.",children:(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,s.jsx)(q.Z,{style:{marginLeft:"4px"}})})})]}),eN?(0,s.jsx)(ev.Z.Item,{name:"litellm_extra_params",rules:[{validator:l_.Ac}],children:(0,s.jsx)(eA.default.TextArea,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}):(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(0,s.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(er.litellm_params,null,2)})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(H.Z,{className:"font-medium",children:"Team ID"}),(0,s.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:eJ.model_info.team_id||"Not Set"})]})]}),eN&&(0,s.jsxs)("div",{className:"mt-6 flex justify-end gap-2",children:[(0,s.jsx)(A.Z,{variant:"secondary",onClick:()=>{ea.resetFields(),ef(!1),ew(!1)},disabled:ej,children:"Cancel"}),(0,s.jsx)(A.Z,{variant:"primary",onClick:()=>ea.submit(),loading:ej,children:"Save Changes"})]})]})}):(0,s.jsx)(H.Z,{children:"Loading..."})]})]}),(0,s.jsx)(U.Z,{children:(0,s.jsx)(lH.Z,{children:(0,s.jsx)("pre",{className:"bg-gray-100 p-4 rounded text-xs overflow-auto",children:JSON.stringify(eJ,null,2)})})})]})]}),(0,s.jsx)(e_.Z,{isOpen:eo,title:"Delete Model",alertMessage:"This action cannot be undone.",message:"Are you sure you want to delete this model?",resourceInformationTitle:"Model Information",resourceInformation:[{label:"Model Name",value:(null==eJ?void 0:eJ.model_name)||"Not Set"},{label:"LiteLLM Model Name",value:(null==eJ?void 0:eJ.litellm_model_name)||"Not Set"},{label:"Provider",value:(null==eJ?void 0:eJ.provider)||"Not Set"},{label:"Created By",value:(null==eJ?void 0:null===(J=eJ.model_info)||void 0===J?void 0:J.created_by)||"Not Set"}],onCancel:()=>ed(!1),onOk:e2,confirmLoading:em}),eh&&!eX?(0,s.jsx)(l0,{isVisible:eh,onCancel:()=>ep(!1),onAddCredential:eQ,existingCredential:eZ,setIsCredentialModalOpen:ep}):(0,s.jsx)(ei.Z,{open:eh,onCancel:()=>ep(!1),title:"Using Existing Credential",children:(0,s.jsx)(H.Z,{children:eJ.litellm_params.litellm_credential_name})}),(0,s.jsx)(l$,{isVisible:eM,onCancel:()=>eL(!1),onSuccess:e=>{en(e),et&&et(e)},modelData:er||eJ,accessToken:X||"",userRole:el||""})]})}var l2=t(27593),l4=t(56147),l5=e=>{var l;let{premiumUser:t,teams:r}=e,{accessToken:i,token:o,userRole:c,userId:x}=(0,n.Z)(),[p]=ev.Z.useForm(),[g,j]=(0,f.useState)(""),[v,_]=(0,f.useState)([]),[y,b]=(0,f.useState)(ex.Cl.Anthropic),[N,w]=(0,f.useState)(null),[Z,C]=(0,f.useState)(null),[k,S]=(0,f.useState)(null),[P,A]=(0,f.useState)(0),[L,F]=(0,f.useState)({}),[I,T]=(0,f.useState)(!1),[R,z]=(0,f.useState)(null),[O,q]=(0,f.useState)(null),[B,G]=(0,f.useState)(0),K=(0,eD.NL)(),{data:J,isLoading:W,refetch:Y}=(0,u.XP)(),{data:Q,isLoading:ee}=m(),{data:el,isLoading:es}=d(),ea=(null==el?void 0:el.credentials)||[],{data:er,isLoading:ei}=(0,h.L)(),en=(0,f.useMemo)(()=>{if(!(null==J?void 0:J.data))return[];let e=new Set;for(let l of J.data)e.add(l.model_name);return Array.from(e).sort()},[null==J?void 0:J.data]),eo=(0,f.useMemo)(()=>{if(!(null==J?void 0:J.data))return[];let e=new Set;for(let l of J.data){let t=l.model_info;if(null==t?void 0:t.access_groups)for(let l of t.access_groups)e.add(l)}return Array.from(e)},[null==J?void 0:J.data]),ed=(0,f.useMemo)(()=>(null==J?void 0:J.data)?J.data.map(e=>e.model_name):[],[null==J?void 0:J.data]),em=e=>null!=Q&&"object"==typeof Q&&e in Q?Q[e].litellm_provider:"openai",eu=(0,f.useMemo)(()=>(null==J?void 0:J.data)?$(J,em):{data:[]},[null==J?void 0:J.data,em]),ep=c&&(0,eV.P4)(c),ef=c&&eV.lo.includes(c),ej=x&&(0,eV.yV)(r,x),e_=ef&&(null==er?void 0:null===(l=er.values)||void 0===l?void 0:l.disable_model_add_for_internal_users)===!0,ey=!ep&&(e_||!ej),eb={name:"file",accept:".json",pastable:!1,beforeUpload:e=>{if("application/json"===e.type){let l=new FileReader;l.onload=e=>{if(e.target){let l=e.target.result;p.setFieldsValue({vertex_credentials:l})}},l.readAsText(e)}return!1},onChange(e){"done"===e.file.status?ec.ZP.success("".concat(e.file.name," file uploaded successfully")):"error"===e.file.status&&ec.ZP.fromBackend("".concat(e.file.name," file upload failed."))}},eN=()=>{j(new Date().toLocaleString()),K.invalidateQueries({queryKey:["models","list"]}),Y()},ew=async()=>{if(i)try{let e={router_settings:{}};"global"===N?(k&&(e.router_settings.retry_policy=k),ec.ZP.success("Global retry settings saved successfully")):(Z&&(e.router_settings.model_group_retry_policy=Z),ec.ZP.success("Retry settings saved successfully for ".concat(N))),await (0,a.setCallbacksCall)(i,e)}catch(e){ec.ZP.fromBackend("Failed to save retry settings")}};if((0,f.useEffect)(()=>{if(!i||!o||!c||!x||!J)return;let e=async()=>{try{let e=(await (0,a.getCallbacksCall)(i,x,c)).router_settings,l=e.model_group_retry_policy,t=e.num_retries;C(l),S(e.retry_policy),A(t);let s=e.model_group_alias||{};F(s)}catch(e){console.error("Error fetching model data:",e)}};i&&o&&c&&x&&J&&e()},[i,o,c,x,J]),c&&"Admin Viewer"==c){let{Title:e,Paragraph:l}=M.default;return(0,s.jsxs)("div",{children:[(0,s.jsx)(e,{level:1,children:"Access Denied"}),(0,s.jsx)(l,{children:"Ask your proxy admin for access to view all models"})]})}let eZ=async()=>{try{let e=await p.validateFields();await eg(e,i,p,eN)}catch(t){var e;let l=(null===(e=t.errorFields)||void 0===e?void 0:e.map(e=>"".concat(e.name.join("."),": ").concat(e.errors.join(", "))).join(" | "))||"Unknown validation error";ec.ZP.fromBackend("Please fill in the following required fields: ".concat(l))}};return(Object.keys(ex.Cl).find(e=>ex.Cl[e]===y),O)?(0,s.jsx)("div",{className:"w-full h-full",children:(0,s.jsx)(l4.Z,{teamId:O,onClose:()=>q(null),accessToken:i,is_team_admin:"Admin"===c,is_proxy_admin:"Proxy Admin"===c,userModels:ed,editTeam:!1,onUpdate:eN,premiumUser:t})}):(0,s.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,s.jsx)(D.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,s.jsxs)(eB.Z,{numColSpan:1,className:"flex flex-col gap-2",children:[(0,s.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,s.jsxs)("div",{children:[(0,s.jsx)("h2",{className:"text-lg font-semibold",children:"Model Management"}),eV.ZL.includes(c)?(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"Add and manage models for the proxy"}):(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"Add models for teams you are an admin for."})]})}),(0,s.jsxs)("div",{className:"mb-4 px-4 py-3 bg-blue-50 rounded-lg border border-blue-100 flex items-center gap-4",children:[(0,s.jsx)("div",{className:"flex-shrink-0 w-10 h-10 bg-white rounded-full flex items-center justify-center border border-blue-200",children:(0,s.jsx)(eJ.Z,{style:{fontSize:"18px",color:"#6366f1"}})}),(0,s.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,s.jsx)("h4",{className:"text-gray-900 font-semibold text-sm m-0",children:"Missing a provider?"}),(0,s.jsx)("p",{className:"text-gray-500 text-xs m-0 mt-0.5",children:"The LiteLLM engineering team is constantly adding support for new LLM models, providers, endpoints. If you don't see the one you need, let us know and we'll prioritize it."})]}),(0,s.jsxs)("a",{href:"https://models.litellm.ai/?request=true",target:"_blank",rel:"noopener noreferrer",className:"flex-shrink-0 inline-flex items-center gap-2 px-4 py-2 bg-[#6366f1] hover:bg-[#5558e3] text-white text-sm font-medium rounded-lg transition-colors",children:["Request Provider",(0,s.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:(0,s.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})]}),R&&!(W||ee||es||ei)?(0,s.jsx)(l1,{modelId:R,onClose:()=>{z(null)},accessToken:i,userID:x,userRole:c,onModelUpdate:e=>{K.invalidateQueries({queryKey:["models","list"]}),eN()},modelAccessGroups:eo}):(0,s.jsxs)(eU.Z,{index:B,onIndexChange:G,className:"gap-2 h-[75vh] w-full ",children:[(0,s.jsxs)(eH.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,s.jsxs)("div",{className:"flex",children:[eV.ZL.includes(c)?(0,s.jsx)(eG.Z,{children:"All Models"}):(0,s.jsx)(eG.Z,{children:"Your Models"}),!ey&&(0,s.jsx)(eG.Z,{children:"Add Model"}),eV.ZL.includes(c)&&(0,s.jsx)(eG.Z,{children:"LLM Credentials"}),eV.ZL.includes(c)&&(0,s.jsx)(eG.Z,{children:"Pass-Through Endpoints"}),eV.ZL.includes(c)&&(0,s.jsx)(eG.Z,{children:"Health Status"}),eV.ZL.includes(c)&&(0,s.jsx)(eG.Z,{children:"Model Retry Settings"}),eV.ZL.includes(c)&&(0,s.jsx)(eG.Z,{children:"Model Group Alias"}),eV.ZL.includes(c)&&(0,s.jsx)(eG.Z,{children:"Price Data Reload"})]}),(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[g&&(0,s.jsxs)(H.Z,{children:["Last Refreshed: ",g]}),(0,s.jsx)(E.Z,{icon:eq.Z,variant:"shadow",size:"xs",className:"self-center",onClick:eN})]})]}),(0,s.jsxs)(eK.Z,{children:[(0,s.jsx)(X,{selectedModelGroup:N,setSelectedModelGroup:w,availableModelGroups:en,availableModelAccessGroups:eo,setSelectedModelId:z,setSelectedTeamId:q}),!ey&&(0,s.jsx)(U.Z,{className:"h-full",children:(0,s.jsx)(lM,{form:p,handleOk:eZ,selectedProvider:y,setSelectedProvider:b,providerModels:v,setProviderModelsFn:e=>{_((0,ex.bK)(e,Q))},getPlaceholder:ex.ph,uploadProps:eb,showAdvancedSettings:I,setShowAdvancedSettings:T,teams:r,credentials:ea,accessToken:i,userRole:c})}),(0,s.jsx)(U.Z,{children:(0,s.jsx)(eO,{uploadProps:eb})}),(0,s.jsx)(U.Z,{children:(0,s.jsx)(l2.Z,{accessToken:i,userRole:c,userID:x,modelData:eu,premiumUser:t})}),(0,s.jsx)(U.Z,{children:(0,s.jsx)(lO,{accessToken:i,modelData:eu,all_models_on_proxy:ed,getDisplayModelName:V,setSelectedModelId:z,teams:r})}),(0,s.jsx)(et,{selectedModelGroup:N,setSelectedModelGroup:w,availableModelGroups:en,globalRetryPolicy:k,setGlobalRetryPolicy:S,defaultRetry:P,modelGroupRetryPolicy:Z,setModelGroupRetryPolicy:C,handleSaveRetrySettings:ew}),(0,s.jsx)(U.Z,{children:(0,s.jsx)(lG,{accessToken:i,initialModelGroupAlias:L,onAliasUpdate:F})}),(0,s.jsx)(eh,{})]})]})]})})})}},45188:function(e,l,t){t.d(l,{K:function(){return i}});var s=t(57437),a=t(2265),r=t(42673);let i=e=>{let{provider:l,className:t="w-4 h-4"}=e,[i,n]=(0,a.useState)(!1),{logo:o}=(0,r.dr)(l);return i||!o?(0,s.jsx)("div",{className:"".concat(t," rounded-full bg-gray-200 flex items-center justify-center text-xs"),children:(null==l?void 0:l.charAt(0))||"-"}):(0,s.jsx)("img",{src:o,alt:"".concat(l," logo"),className:t,onError:()=>n(!0)})}},27593:function(e,l,t){t.d(l,{Z:function(){return Y}});var s=t(57437),a=t(2265),r=t(78489),i=t(47323),n=t(84264),o=t(96761),d=t(19250),c=t(99981),m=t(33866),u=t(15731),h=t(53410),x=t(74998),p=t(59341),g=t(49566),f=t(12514),j=t(97765),v=t(37592),_=t(10032),y=t(22116),b=t(51653),N=t(24199),w=t(12660),Z=t(15424),C=t(55590),k=t(5545),S=t(45246),P=t(96473),A=t(31283),E=e=>{let{value:l={},onChange:t}=e,[r,i]=(0,a.useState)(Object.entries(l)),n=e=>{let l=r.filter((l,t)=>t!==e);i(l),null==t||t(Object.fromEntries(l))},o=(e,l,s)=>{let a=[...r];a[e]=[l,s],i(a),null==t||t(Object.fromEntries(a))};return(0,s.jsxs)("div",{children:[r.map((e,l)=>{let[t,a]=e;return(0,s.jsxs)(C.Z,{style:{display:"flex",marginBottom:8},align:"center",children:[(0,s.jsx)(A.o,{placeholder:"Header Name",value:t,onChange:e=>o(l,e.target.value,a)}),(0,s.jsx)(A.o,{placeholder:"Header Value",value:a,onChange:e=>o(l,t,e.target.value)}),(0,s.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,s.jsx)(S.Z,{onClick:()=>n(l),style:{cursor:"pointer"}})})]},l)}),(0,s.jsx)(k.ZP,{type:"dashed",onClick:()=>{i([...r,["",""]])},icon:(0,s.jsx)(P.Z,{}),children:"Add Header"})]})},M=t(77565),L=e=>{let{pathValue:l,targetValue:t,includeSubpath:a}=e,r=(0,d.getProxyBaseUrl)();return l&&t?(0,s.jsxs)(f.Z,{className:"p-5",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Route Preview"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-5",children:"How your requests will be routed"}),(0,s.jsxs)("div",{className:"space-y-5",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"text-base font-semibold text-gray-900 mb-3",children:"Basic routing:"}),(0,s.jsxs)("div",{className:"flex items-center gap-4",children:[(0,s.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,s.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Your endpoint"}),(0,s.jsx)("code",{className:"font-mono text-sm text-gray-900",children:l?"".concat(r).concat(l):""})]}),(0,s.jsx)("div",{className:"text-gray-400",children:(0,s.jsx)(M.Z,{className:"text-lg"})}),(0,s.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,s.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Forwards to"}),(0,s.jsx)("code",{className:"font-mono text-sm text-gray-900",children:t})]})]})]}),a&&(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"text-base font-semibold text-gray-900 mb-3",children:"With subpaths:"}),(0,s.jsxs)("div",{className:"flex items-center gap-4",children:[(0,s.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,s.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Your endpoint + subpath"}),(0,s.jsxs)("code",{className:"font-mono text-sm text-gray-900",children:[l&&"".concat(r).concat(l),(0,s.jsx)("span",{className:"text-blue-600",children:"/v1/text-to-image/base/model"})]})]}),(0,s.jsx)("div",{className:"text-gray-400",children:(0,s.jsx)(M.Z,{className:"text-lg"})}),(0,s.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,s.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Forwards to"}),(0,s.jsxs)("code",{className:"font-mono text-sm text-gray-900",children:[t,(0,s.jsx)("span",{className:"text-blue-600",children:"/v1/text-to-image/base/model"})]})]})]}),(0,s.jsxs)("div",{className:"mt-3 text-sm text-gray-600",children:["Any path after ",l," will be appended to the target URL"]})]})}),!a&&(0,s.jsx)("div",{className:"mt-4 p-3 bg-blue-50 rounded-md border border-blue-200",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(Z.Z,{className:"text-blue-500 mt-0.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{className:"text-sm text-blue-700",children:[(0,s.jsx)("span",{className:"font-medium",children:"Not seeing the routing you wanted?"})," Try enabling - Include Subpaths - above - this allows subroutes like"," ",(0,s.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded font-mono text-xs",children:"/api/v1/models"})," to be forwarded automatically."]})]})})]})]}):null},F=t(9114),I=t(63709),T=e=>{let{premiumUser:l,authEnabled:t,onAuthChange:a}=e;return(0,s.jsxs)(f.Z,{className:"p-6",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Security"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-4",children:"When enabled, requests to this endpoint will require a valid LiteLLM Virtual Key"}),l?(0,s.jsx)(_.Z.Item,{name:"auth",valuePropName:"checked",className:"mb-0",children:(0,s.jsx)(I.Z,{checked:t,onChange:e=>{a(e)}})}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center mb-3",children:[(0,s.jsx)(I.Z,{disabled:!0,checked:!1,style:{outline:"2px solid #d1d5db",outlineOffset:"2px"}}),(0,s.jsx)("span",{className:"ml-2 text-sm text-gray-400",children:"Authentication (Premium)"})]}),(0,s.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,s.jsxs)(n.Z,{className:"text-sm text-yellow-800",children:["Setting authentication for pass-through endpoints is a LiteLLM Enterprise feature. Get a trial key"," ",(0,s.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})]})},R=t(67479),z=e=>{let{accessToken:l,value:t={},onChange:r,disabled:i=!1}=e,[n,d]=(0,a.useState)(Object.keys(t)),[m,u]=(0,a.useState)(t);(0,a.useEffect)(()=>{u(t),d(Object.keys(t))},[t]);let h=(e,l,t)=>{var s,a;let i=m[e]||{},n={...m,[e]:{...i,[l]:t.length>0?t:void 0}};(null===(s=n[e])||void 0===s?void 0:s.request_fields)||(null===(a=n[e])||void 0===a?void 0:a.response_fields)||(n[e]=null),u(n),r&&r(n)};return(0,s.jsxs)(f.Z,{className:"p-6",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Guardrails"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-6",children:"Configure guardrails to enforce policies on requests and responses. Guardrails are opt-in for passthrough endpoints."}),(0,s.jsx)(b.Z,{message:(0,s.jsxs)("span",{children:["Field-Level Targeting"," ",(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through_guardrails#field-level-targeting",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"(Learn More)"})]}),description:(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsx)("div",{children:"Optionally specify which fields to check. If left empty, the entire request/response is sent to the guardrail."}),(0,s.jsxs)("div",{className:"text-xs space-y-1 mt-2",children:[(0,s.jsx)("div",{className:"font-medium",children:"Common Examples:"}),(0,s.jsxs)("div",{children:["• ",(0,s.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"query"})," - Single field"]}),(0,s.jsxs)("div",{children:["• ",(0,s.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"documents[*].text"})," - All text in documents array"]}),(0,s.jsxs)("div",{children:["• ",(0,s.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"messages[*].content"})," - All message contents"]})]})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,s.jsx)(_.Z.Item,{label:(0,s.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Select Guardrails",(0,s.jsx)(c.Z,{title:"Choose which guardrails should run on this endpoint. Org/team/key level guardrails will also be included.",children:(0,s.jsx)(Z.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),children:(0,s.jsx)(R.Z,{accessToken:l,value:n,onChange:e=>{d(e);let l={};e.forEach(e=>{l[e]=m[e]||null}),u(l),r&&r(l)},disabled:i})}),n.length>0&&(0,s.jsxs)("div",{className:"mt-6 space-y-4",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between mb-3",children:[(0,s.jsx)("div",{className:"text-sm font-medium text-gray-700",children:"Field Targeting (Optional)"}),(0,s.jsx)("div",{className:"text-xs text-gray-500",children:"\uD83D\uDCA1 Tip: Leave empty to check entire payload"})]}),n.map(e=>{var l,t;return(0,s.jsxs)(f.Z,{className:"p-4 bg-gray-50",children:[(0,s.jsx)("div",{className:"text-sm font-medium text-gray-900 mb-3",children:e}),(0,s.jsxs)("div",{className:"space-y-3",children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,s.jsxs)("label",{className:"text-xs text-gray-600 flex items-center",children:["Request Fields (pre_call)",(0,s.jsx)(c.Z,{title:(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"font-medium mb-1",children:"Specify which request fields to check"}),(0,s.jsxs)("div",{className:"text-xs space-y-1",children:[(0,s.jsx)("div",{children:"Examples:"}),(0,s.jsx)("div",{children:"• query"}),(0,s.jsx)("div",{children:"• documents[*].text"}),(0,s.jsx)("div",{children:"• messages[*].content"})]})]}),children:(0,s.jsx)(Z.Z,{className:"ml-1 text-gray-400"})})]}),(0,s.jsxs)("div",{className:"flex gap-1",children:[(0,s.jsx)("button",{type:"button",onClick:()=>{var l;let t=(null===(l=m[e])||void 0===l?void 0:l.request_fields)||[];h(e,"request_fields",[...t,"query"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:i,children:"+ query"}),(0,s.jsx)("button",{type:"button",onClick:()=>{var l;let t=(null===(l=m[e])||void 0===l?void 0:l.request_fields)||[];h(e,"request_fields",[...t,"documents[*]"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:i,children:"+ documents[*]"})]})]}),(0,s.jsx)(v.default,{mode:"tags",style:{width:"100%"},placeholder:"Type field name or use + buttons above (e.g., query, documents[*].text)",value:(null===(l=m[e])||void 0===l?void 0:l.request_fields)||[],onChange:l=>h(e,"request_fields",l),disabled:i,tokenSeparators:[","]})]}),(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,s.jsxs)("label",{className:"text-xs text-gray-600 flex items-center",children:["Response Fields (post_call)",(0,s.jsx)(c.Z,{title:(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"font-medium mb-1",children:"Specify which response fields to check"}),(0,s.jsxs)("div",{className:"text-xs space-y-1",children:[(0,s.jsx)("div",{children:"Examples:"}),(0,s.jsx)("div",{children:"• results[*].text"}),(0,s.jsx)("div",{children:"• choices[*].message.content"})]})]}),children:(0,s.jsx)(Z.Z,{className:"ml-1 text-gray-400"})})]}),(0,s.jsx)("div",{className:"flex gap-1",children:(0,s.jsx)("button",{type:"button",onClick:()=>{var l;let t=(null===(l=m[e])||void 0===l?void 0:l.response_fields)||[];h(e,"response_fields",[...t,"results[*]"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:i,children:"+ results[*]"})})]}),(0,s.jsx)(v.default,{mode:"tags",style:{width:"100%"},placeholder:"Type field name or use + buttons above (e.g., results[*].text)",value:(null===(t=m[e])||void 0===t?void 0:t.response_fields)||[],onChange:l=>h(e,"response_fields",l),disabled:i,tokenSeparators:[","]})]})]})]},e)})]})]})};let{Option:O}=v.default;var V=e=>{let{accessToken:l,setPassThroughItems:t,passThroughItems:i,premiumUser:n=!1}=e,[m]=_.Z.useForm(),[u,h]=(0,a.useState)(!1),[x,v]=(0,a.useState)(!1),[C,k]=(0,a.useState)(""),[S,P]=(0,a.useState)(""),[A,M]=(0,a.useState)(""),[I,R]=(0,a.useState)(!0),[O,V]=(0,a.useState)(!1),[q,D]=(0,a.useState)({}),B=()=>{m.resetFields(),P(""),M(""),R(!0),D({}),h(!1)},G=e=>{let l=e;e&&!e.startsWith("/")&&(l="/"+e),P(l),m.setFieldsValue({path:l})},U=async e=>{console.log("addPassThrough called with:",e),v(!0);try{!n&&"auth"in e&&delete e.auth,q&&Object.keys(q).length>0&&(e.guardrails=q),console.log("formValues: ".concat(JSON.stringify(e)));let s=(await (0,d.createPassThroughEndpoint)(l,e)).endpoints[0],a=[...i,s];t(a),F.ZP.success("Pass-through endpoint created successfully"),m.resetFields(),P(""),M(""),R(!0),D({}),h(!1)}catch(e){F.ZP.fromBackend("Error creating pass-through endpoint: "+e)}finally{v(!1)}};return(0,s.jsxs)("div",{children:[(0,s.jsx)(r.Z,{className:"mx-auto mb-4 mt-4",onClick:()=>h(!0),children:"+ Add Pass-Through Endpoint"}),(0,s.jsx)(y.Z,{title:(0,s.jsxs)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:[(0,s.jsx)(w.Z,{className:"text-xl text-blue-500"}),(0,s.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Pass-Through Endpoint"})]}),open:u,width:1e3,onCancel:B,footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,s.jsxs)("div",{className:"mt-6",children:[(0,s.jsx)(b.Z,{message:"What is a Pass-Through Endpoint?",description:"Route requests from your LiteLLM proxy to any external API. Perfect for custom models, image generation APIs, or any service you want to proxy through LiteLLM.",type:"info",showIcon:!0,className:"mb-6"}),(0,s.jsxs)(_.Z,{form:m,onFinish:U,layout:"vertical",className:"space-y-6",initialValues:{include_subpath:!0,path:S,target:A},children:[(0,s.jsxs)(f.Z,{className:"p-5",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Route Configuration"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-5",children:"Configure how requests to your domain will be forwarded to the target API"}),(0,s.jsxs)("div",{className:"space-y-5",children:[(0,s.jsx)(_.Z.Item,{label:(0,s.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Path Prefix"}),name:"path",rules:[{required:!0,message:"Path is required",pattern:/^\//}],extra:(0,s.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:"Example: /bria, /adobe-photoshop, /elasticsearch"}),className:"mb-4",children:(0,s.jsx)("div",{className:"flex items-center",children:(0,s.jsx)(g.Z,{placeholder:"bria",value:S,onChange:e=>G(e.target.value),className:"flex-1"})})}),(0,s.jsx)(_.Z.Item,{label:(0,s.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Target URL"}),name:"target",rules:[{required:!0,message:"Target URL is required"},{type:"url",message:"Please enter a valid URL"}],extra:(0,s.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:"Example:https://engine.prod.bria-api.com"}),className:"mb-4",children:(0,s.jsx)(g.Z,{placeholder:"https://engine.prod.bria-api.com",value:A,onChange:e=>{M(e.target.value),m.setFieldsValue({target:e.target.value})}})}),(0,s.jsxs)("div",{className:"flex items-center justify-between py-3",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"text-sm font-medium text-gray-700",children:"Include Subpaths"}),(0,s.jsx)("div",{className:"text-xs text-gray-500 mt-0.5",children:"Forward all subpaths to the target API (recommended for REST APIs)"})]}),(0,s.jsx)(_.Z.Item,{name:"include_subpath",valuePropName:"checked",className:"mb-0",children:(0,s.jsx)(p.Z,{checked:I,onChange:R})})]})]})]}),(0,s.jsx)(L,{pathValue:S,targetValue:A,includeSubpath:I}),(0,s.jsxs)(f.Z,{className:"p-6",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Headers"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-6",children:"Add headers that will be sent with every request to the target API"}),(0,s.jsx)(_.Z.Item,{label:(0,s.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Authentication Headers",(0,s.jsx)(c.Z,{title:"Authentication and other headers to forward with requests",children:(0,s.jsx)(Z.Z,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"headers",rules:[{required:!0,message:"Please configure the headers"}],extra:(0,s.jsxs)("div",{className:"text-xs text-gray-500 mt-2",children:[(0,s.jsx)("div",{className:"font-medium mb-1",children:"Add authentication tokens and other required headers"}),(0,s.jsx)("div",{children:"Common examples: auth_token, Authorization, x-api-key"})]}),children:(0,s.jsx)(E,{})})]}),(0,s.jsx)(T,{premiumUser:n,authEnabled:O,onAuthChange:e=>{V(e),m.setFieldsValue({auth:e})}}),(0,s.jsx)(z,{accessToken:l,value:q,onChange:D}),(0,s.jsxs)(f.Z,{className:"p-6",children:[(0,s.jsx)(o.Z,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Billing"}),(0,s.jsx)(j.Z,{className:"text-gray-600 mb-6",children:"Optional cost tracking for this endpoint"}),(0,s.jsx)(_.Z.Item,{label:(0,s.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Cost Per Request (USD)",(0,s.jsx)(c.Z,{title:"Optional: Track costs for requests to this endpoint",children:(0,s.jsx)(Z.Z,{className:"ml-2 text-gray-400 hover:text-gray-600"})})]}),name:"cost_per_request",extra:(0,s.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"The cost charged for each request through this endpoint"}),children:(0,s.jsx)(N.Z,{min:0,step:.001,precision:4,placeholder:"2.0000",size:"large"})})]}),(0,s.jsxs)("div",{className:"flex items-center justify-end space-x-3 pt-6 border-t border-gray-100",children:[(0,s.jsx)(r.Z,{variant:"secondary",onClick:B,children:"Cancel"}),(0,s.jsx)(r.Z,{variant:"primary",loading:x,onClick:()=>{console.log("Submit button clicked"),m.submit()},children:x?"Creating...":"Add Pass-Through Endpoint"})]})]})]})})]})},q=t(30078),D=t(4260),B=t(12221),G=t(87769),U=t(42208);let H=e=>{let{value:l}=e,[t,r]=(0,a.useState)(!1),i=JSON.stringify(l,null,2);return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("pre",{className:"font-mono text-xs bg-gray-50 p-2 rounded max-w-md overflow-auto",children:t?i:"••••••••"}),(0,s.jsx)("button",{onClick:()=>r(!t),className:"p-1 hover:bg-gray-100 rounded",type:"button",children:t?(0,s.jsx)(G.Z,{className:"w-4 h-4 text-gray-500"}):(0,s.jsx)(U.Z,{className:"w-4 h-4 text-gray-500"})})]})};var K=e=>{let{endpointData:l,onClose:t,accessToken:r,isAdmin:i,premiumUser:n=!1,onEndpointUpdated:o}=e,[c,m]=(0,a.useState)(l),[u,h]=(0,a.useState)(!1),[x,p]=(0,a.useState)(!1),[g,f]=(0,a.useState)((null==l?void 0:l.auth)||!1),[j,v]=(0,a.useState)((null==l?void 0:l.guardrails)||{}),[y]=_.Z.useForm(),b=async e=>{try{if(!r||!(null==c?void 0:c.id))return;let l={};if(e.headers)try{l="string"==typeof e.headers?JSON.parse(e.headers):e.headers}catch(e){F.ZP.fromBackend("Invalid JSON format for headers");return}let t={path:c.path,target:e.target,headers:l,include_subpath:e.include_subpath,cost_per_request:e.cost_per_request,auth:n?e.auth:void 0,guardrails:j&&Object.keys(j).length>0?j:void 0};await (0,d.updatePassThroughEndpoint)(r,c.id,t),m({...c,...t}),p(!1),o&&o()}catch(e){console.error("Error updating endpoint:",e),F.ZP.fromBackend("Failed to update pass through endpoint")}},N=async()=>{try{if(!r||!(null==c?void 0:c.id))return;await (0,d.deletePassThroughEndpointsCall)(r,c.id),F.ZP.success("Pass through endpoint deleted successfully"),t(),o&&o()}catch(e){console.error("Error deleting endpoint:",e),F.ZP.fromBackend("Failed to delete pass through endpoint")}};return u?(0,s.jsx)("div",{className:"p-4",children:"Loading..."}):c?(0,s.jsxs)("div",{className:"p-4",children:[(0,s.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,s.jsxs)("div",{children:[(0,s.jsx)(k.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,s.jsxs)(q.Dx,{children:["Pass Through Endpoint: ",c.path]}),(0,s.jsx)(q.xv,{className:"text-gray-500 font-mono",children:c.id})]})}),(0,s.jsxs)(q.v0,{children:[(0,s.jsxs)(q.td,{className:"mb-4",children:[(0,s.jsx)(q.OK,{children:"Overview"},"overview"),i?(0,s.jsx)(q.OK,{children:"Settings"},"settings"):(0,s.jsx)(s.Fragment,{})]}),(0,s.jsxs)(q.nP,{children:[(0,s.jsxs)(q.x4,{children:[(0,s.jsxs)(q.rj,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,s.jsxs)(q.Zb,{children:[(0,s.jsx)(q.xv,{children:"Path"}),(0,s.jsx)("div",{className:"mt-2",children:(0,s.jsx)(q.Dx,{className:"font-mono",children:c.path})})]}),(0,s.jsxs)(q.Zb,{children:[(0,s.jsx)(q.xv,{children:"Target"}),(0,s.jsx)("div",{className:"mt-2",children:(0,s.jsx)(q.Dx,{children:c.target})})]}),(0,s.jsxs)(q.Zb,{children:[(0,s.jsx)(q.xv,{children:"Configuration"}),(0,s.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,s.jsx)("div",{children:(0,s.jsx)(q.Ct,{color:c.include_subpath?"green":"gray",children:c.include_subpath?"Include Subpath":"Exact Path"})}),(0,s.jsx)("div",{children:(0,s.jsx)(q.Ct,{color:c.auth?"blue":"gray",children:c.auth?"Auth Required":"No Auth"})}),void 0!==c.cost_per_request&&(0,s.jsx)("div",{children:(0,s.jsxs)(q.xv,{children:["Cost per request: $",c.cost_per_request]})})]})]})]}),(0,s.jsx)("div",{className:"mt-6",children:(0,s.jsx)(L,{pathValue:c.path,targetValue:c.target,includeSubpath:c.include_subpath||!1})}),c.headers&&Object.keys(c.headers).length>0&&(0,s.jsxs)(q.Zb,{className:"mt-6",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(q.xv,{className:"font-medium",children:"Headers"}),(0,s.jsxs)(q.Ct,{color:"blue",children:[Object.keys(c.headers).length," headers configured"]})]}),(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(H,{value:c.headers})})]}),c.guardrails&&Object.keys(c.guardrails).length>0&&(0,s.jsxs)(q.Zb,{className:"mt-6",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)(q.xv,{className:"font-medium",children:"Guardrails"}),(0,s.jsxs)(q.Ct,{color:"purple",children:[Object.keys(c.guardrails).length," guardrails configured"]})]}),(0,s.jsx)("div",{className:"mt-4 space-y-2",children:Object.entries(c.guardrails).map(e=>{let[l,t]=e;return(0,s.jsxs)("div",{className:"p-3 bg-gray-50 rounded",children:[(0,s.jsx)("div",{className:"font-medium text-sm",children:l}),t&&(t.request_fields||t.response_fields)&&(0,s.jsxs)("div",{className:"mt-2 text-xs text-gray-600 space-y-1",children:[t.request_fields&&(0,s.jsxs)("div",{children:["Request fields: ",t.request_fields.join(", ")]}),t.response_fields&&(0,s.jsxs)("div",{children:["Response fields: ",t.response_fields.join(", ")]})]}),!t&&(0,s.jsx)("div",{className:"text-xs text-gray-600 mt-1",children:"Uses entire payload"})]},l)})})]})]}),i&&(0,s.jsx)(q.x4,{children:(0,s.jsxs)(q.Zb,{children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,s.jsx)(q.Dx,{children:"Pass Through Endpoint Settings"}),(0,s.jsx)("div",{className:"space-x-2",children:!x&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(q.zx,{onClick:()=>p(!0),children:"Edit Settings"}),(0,s.jsx)(q.zx,{onClick:N,variant:"secondary",color:"red",children:"Delete Endpoint"})]})})]}),x?(0,s.jsxs)(_.Z,{form:y,onFinish:b,initialValues:{target:c.target,headers:c.headers?JSON.stringify(c.headers,null,2):"",include_subpath:c.include_subpath||!1,cost_per_request:c.cost_per_request,auth:c.auth||!1},layout:"vertical",children:[(0,s.jsx)(_.Z.Item,{label:"Target URL",name:"target",rules:[{required:!0,message:"Please input a target URL"}],children:(0,s.jsx)(q.oi,{placeholder:"https://api.example.com"})}),(0,s.jsx)(_.Z.Item,{label:"Headers (JSON)",name:"headers",children:(0,s.jsx)(D.default.TextArea,{rows:5,placeholder:'{"Authorization": "Bearer your-token", "Content-Type": "application/json"}'})}),(0,s.jsx)(_.Z.Item,{label:"Include Subpath",name:"include_subpath",valuePropName:"checked",children:(0,s.jsx)(I.Z,{})}),(0,s.jsx)(_.Z.Item,{label:"Cost per Request",name:"cost_per_request",children:(0,s.jsx)(B.Z,{min:0,step:.01,precision:2,placeholder:"0.00",addonBefore:"$"})}),(0,s.jsx)(T,{premiumUser:n,authEnabled:g,onAuthChange:e=>{f(e),y.setFieldsValue({auth:e})}}),(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(z,{accessToken:r||"",value:j,onChange:v})}),(0,s.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,s.jsx)(k.ZP,{onClick:()=>p(!1),children:"Cancel"}),(0,s.jsx)(q.zx,{children:"Save Changes"})]})]}):(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(q.xv,{className:"font-medium",children:"Path"}),(0,s.jsx)("div",{className:"font-mono",children:c.path})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(q.xv,{className:"font-medium",children:"Target URL"}),(0,s.jsx)("div",{children:c.target})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(q.xv,{className:"font-medium",children:"Include Subpath"}),(0,s.jsx)(q.Ct,{color:c.include_subpath?"green":"gray",children:c.include_subpath?"Yes":"No"})]}),void 0!==c.cost_per_request&&(0,s.jsxs)("div",{children:[(0,s.jsx)(q.xv,{className:"font-medium",children:"Cost per Request"}),(0,s.jsxs)("div",{children:["$",c.cost_per_request]})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(q.xv,{className:"font-medium",children:"Authentication Required"}),(0,s.jsx)(q.Ct,{color:c.auth?"green":"gray",children:c.auth?"Yes":"No"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(q.xv,{className:"font-medium",children:"Headers"}),c.headers&&Object.keys(c.headers).length>0?(0,s.jsx)("div",{className:"mt-2",children:(0,s.jsx)(H,{value:c.headers})}):(0,s.jsx)("div",{className:"text-gray-500",children:"No headers configured"})]})]})]})})]})]})]}):(0,s.jsx)("div",{className:"p-4",children:"Pass through endpoint not found"})},J=t(60493);let W=e=>{let{value:l}=e,[t,r]=(0,a.useState)(!1),i=JSON.stringify(l);return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("span",{className:"font-mono text-xs",children:t?i:"••••••••"}),(0,s.jsx)("button",{onClick:()=>r(!t),className:"p-1 hover:bg-gray-100 rounded",type:"button",children:t?(0,s.jsx)(G.Z,{className:"w-4 h-4 text-gray-500"}):(0,s.jsx)(U.Z,{className:"w-4 h-4 text-gray-500"})})]})};var Y=e=>{let{accessToken:l,userRole:t,userID:p,modelData:g,premiumUser:f}=e,[j,v]=(0,a.useState)([]),[_,y]=(0,a.useState)(null),[b,N]=(0,a.useState)(!1),[w,Z]=(0,a.useState)(null);(0,a.useEffect)(()=>{l&&t&&p&&(0,d.getPassThroughEndpointsCall)(l).then(e=>{v(e.endpoints)})},[l,t,p]);let C=async e=>{Z(e),N(!0)},k=async()=>{if(null!=w&&l){try{await (0,d.deletePassThroughEndpointsCall)(l,w);let e=j.filter(e=>e.id!==w);v(e),F.ZP.success("Endpoint deleted successfully.")}catch(e){console.error("Error deleting the endpoint:",e),F.ZP.fromBackend("Error deleting the endpoint: "+e)}N(!1),Z(null)}},S=(e,l)=>{C(e)},P=[{header:"ID",accessorKey:"id",cell:e=>(0,s.jsx)(c.Z,{title:e.row.original.id,children:(0,s.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 max-w-[15ch]",onClick:()=>e.row.original.id&&y(e.row.original.id),children:e.row.original.id})})},{header:"Path",accessorKey:"path"},{header:"Target",accessorKey:"target",cell:e=>(0,s.jsx)(n.Z,{children:e.getValue()})},{header:()=>(0,s.jsxs)("div",{className:"flex items-center gap-1",children:[(0,s.jsx)("span",{children:"Authentication"}),(0,s.jsx)(c.Z,{title:"LiteLLM Virtual Key required to call endpoint",children:(0,s.jsx)(u.Z,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),accessorKey:"auth",cell:e=>(0,s.jsx)(m.Z,{color:e.getValue()?"green":"gray",children:e.getValue()?"Yes":"No"})},{header:"Headers",accessorKey:"headers",cell:e=>(0,s.jsx)(W,{value:e.getValue()||{}})},{header:"Actions",id:"actions",cell:e=>{let{row:l}=e;return(0,s.jsxs)("div",{className:"flex space-x-1",children:[(0,s.jsx)(i.Z,{icon:h.Z,size:"sm",onClick:()=>l.original.id&&y(l.original.id),title:"Edit"}),(0,s.jsx)(i.Z,{icon:x.Z,size:"sm",onClick:()=>S(l.original.id,l.index),title:"Delete"})]})}}];if(!l)return null;if(_){console.log("selectedEndpointId",_),console.log("generalSettings",j);let e=j.find(e=>e.id===_);return e?(0,s.jsx)(K,{endpointData:e,onClose:()=>y(null),accessToken:l,isAdmin:"Admin"===t||"admin"===t,premiumUser:f,onEndpointUpdated:()=>{l&&(0,d.getPassThroughEndpointsCall)(l).then(e=>{v(e.endpoints)})}}):(0,s.jsx)("div",{children:"Endpoint not found"})}return(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(o.Z,{children:"Pass Through Endpoints"}),(0,s.jsx)(n.Z,{className:"text-tremor-content",children:"Configure and manage your pass-through endpoints"})]}),(0,s.jsx)(V,{accessToken:l,setPassThroughItems:v,passThroughItems:j,premiumUser:f}),(0,s.jsx)(J.w,{data:j,columns:P,renderSubComponent:()=>(0,s.jsx)("div",{}),getRowCanExpand:()=>!1,isLoading:!1,noDataMessage:"No pass-through endpoints configured"}),b&&(0,s.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,s.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,s.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,s.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,s.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,s.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,s.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,s.jsx)("div",{className:"sm:flex sm:items-start",children:(0,s.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,s.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Pass-Through Endpoint"}),(0,s.jsx)("div",{className:"mt-2",children:(0,s.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this pass-through endpoint? This action cannot be undone."})})]})})}),(0,s.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,s.jsx)(r.Z,{onClick:k,color:"red",className:"ml-2",children:"Delete"}),(0,s.jsx)(r.Z,{onClick:()=>{N(!1),Z(null)},children:"Cancel"})]})]})]})})]})}},60493:function(e,l,t){t.d(l,{w:function(){return o}});var s=t(57437),a=t(2265),r=t(71594),i=t(24525),n=t(19130);function o(e){let{data:l=[],columns:t,onRowClick:o,renderSubComponent:d,getRowCanExpand:c,isLoading:m=!1,loadingMessage:u="\uD83D\uDE85 Loading logs...",noDataMessage:h="No logs found"}=e,x=!!d&&!!c,p=(0,r.b7)({data:l,columns:t,...x&&{getRowCanExpand:c},getRowId:(e,l)=>{var t;return null!==(t=null==e?void 0:e.request_id)&&void 0!==t?t:String(l)},getCoreRowModel:(0,i.sC)(),...x&&{getExpandedRowModel:(0,i.rV)()}});return(0,s.jsx)("div",{className:"rounded-lg custom-border overflow-x-auto w-full max-w-full box-border",children:(0,s.jsxs)(n.iA,{className:"[&_td]:py-0.5 [&_th]:py-1 table-fixed w-full box-border",style:{minWidth:"400px"},children:[(0,s.jsx)(n.ss,{children:p.getHeaderGroups().map(e=>(0,s.jsx)(n.SC,{children:e.headers.map(e=>(0,s.jsx)(n.xs,{className:"py-1 h-8",children:e.isPlaceholder?null:(0,r.ie)(e.column.columnDef.header,e.getContext())},e.id))},e.id))}),(0,s.jsx)(n.RM,{children:m?(0,s.jsx)(n.SC,{children:(0,s.jsx)(n.pj,{colSpan:t.length,className:"h-8 text-center",children:(0,s.jsx)("div",{className:"text-center text-gray-500",children:(0,s.jsx)("p",{children:u})})})}):p.getRowModel().rows.length>0?p.getRowModel().rows.map(e=>(0,s.jsxs)(a.Fragment,{children:[(0,s.jsx)(n.SC,{className:"h-8 ".concat(x?"":"cursor-pointer hover:bg-gray-50"),onClick:()=>!x&&(null==o?void 0:o(e.original)),children:e.getVisibleCells().map(e=>(0,s.jsx)(n.pj,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,r.ie)(e.column.columnDef.cell,e.getContext())},e.id))}),x&&e.getIsExpanded()&&d&&(0,s.jsx)(n.SC,{children:(0,s.jsx)(n.pj,{colSpan:e.getVisibleCells().length,className:"p-0",children:(0,s.jsx)("div",{className:"w-full max-w-full overflow-hidden box-border",children:d({row:e})})})})]},e.id)):(0,s.jsx)(n.SC,{children:(0,s.jsx)(n.pj,{colSpan:t.length,className:"h-8 text-center",children:(0,s.jsx)("div",{className:"text-center text-gray-500",children:(0,s.jsx)("p",{children:h})})})})})]})})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/2117-26a589a1115bdd0a.js b/litellm/proxy/_experimental/out/_next/static/chunks/2117-bb4323b3c0b11a1f.js similarity index 83% rename from litellm/proxy/_experimental/out/_next/static/chunks/2117-26a589a1115bdd0a.js rename to litellm/proxy/_experimental/out/_next/static/chunks/2117-bb4323b3c0b11a1f.js index 10b7be385dc..fae288cfede 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/2117-26a589a1115bdd0a.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/2117-bb4323b3c0b11a1f.js @@ -1,2 +1,2 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2117],{65157:function(e,t){"use strict";function n(){return""}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getDeploymentIdQueryOrEmptyString",{enumerable:!0,get:function(){return n}})},91572:function(){"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var e=/\((.*)\)/.exec(this.toString());return e?e[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(e,t){return t=this.concat.apply([],this),e>1&&t.some(Array.isArray)?t.flat(e-1):t},Array.prototype.flatMap=function(e,t){return this.map(e,t).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(e){if("function"!=typeof e)return this.then(e,e);var t=this.constructor||Promise;return this.then(function(n){return t.resolve(e()).then(function(){return n})},function(n){return t.resolve(e()).then(function(){throw n})})}),Object.fromEntries||(Object.fromEntries=function(e){return Array.from(e).reduce(function(e,t){return e[t[0]]=t[1],e},{})}),Array.prototype.at||(Array.prototype.at=function(e){var t=Math.trunc(e)||0;if(t<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]}),Object.hasOwn||(Object.hasOwn=function(e,t){if(null==e)throw TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(e),t)}),"canParse"in URL||(URL.canParse=function(e,t){try{return new URL(e,t),!0}catch(e){return!1}})},1634:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return u}});let r=n(68498),o=n(33068);function u(e,t){return(0,o.normalizePathTrailingSlash)((0,r.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},75266:function(e,t){"use strict";function n(e){var t,n;t=self.__next_s,n=()=>{e()},t&&t.length?t.reduce((e,t)=>{let[n,r]=t;return e.then(()=>new Promise((e,t)=>{let o=document.createElement("script");if(r)for(let e in r)"children"!==e&&o.setAttribute(e,r[e]);n?(o.src=n,o.onload=()=>e(),o.onerror=t):r&&(o.innerHTML=r.children,setTimeout(e)),document.head.appendChild(o)}))},Promise.resolve()).catch(e=>{console.error(e)}).then(()=>{n()}):n()}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"appBootstrap",{enumerable:!0,get:function(){return n}}),window.next={version:"14.2.35",appDir:!0},("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},83079:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"callServer",{enumerable:!0,get:function(){return o}});let r=n(12846);async function o(e,t){let n=(0,r.getServerActionDispatcher)();if(!n)throw Error("Invariant: missing action dispatcher.");return new Promise((r,o)=>{n({actionId:e,actionArgs:t,resolve:r,reject:o})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},92304:function(e,t,n){"use strict";let r,o;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hydrate",{enumerable:!0,get:function(){return x}});let u=n(47043),l=n(53099),a=n(57437);n(91572);let i=u._(n(34040)),c=l._(n(2265)),s=n(6671),f=n(48701),d=u._(n(61404)),p=n(83079),h=n(89721),y=n(2103);n(70647);let _=window.console.error;window.console.error=function(){for(var e=arguments.length,t=Array(e),n=0;n{if((0,h.isNextRouterError)(e.error)){e.preventDefault();return}});let v=document,b=new TextEncoder,g=!1,m=!1,R=null;function P(e){if(0===e[0])r=[];else if(1===e[0]){if(!r)throw Error("Unexpected server data: missing bootstrap script.");o?o.enqueue(b.encode(e[1])):r.push(e[1])}else 2===e[0]&&(R=e[1])}let j=function(){o&&!m&&(o.close(),m=!0,r=void 0),g=!0};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",j,!1):j();let O=self.__next_f=self.__next_f||[];O.forEach(P),O.push=P;let E=new ReadableStream({start(e){r&&(r.forEach(t=>{e.enqueue(b.encode(t))}),g&&!m&&(e.close(),m=!0,r=void 0)),o=e}}),S=(0,s.createFromReadableStream)(E,{callServer:p.callServer});function w(){return(0,c.use)(S)}let M=c.default.StrictMode;function T(e){let{children:t}=e;return t}function x(){let e=(0,y.createMutableActionQueue)(),t=(0,a.jsx)(M,{children:(0,a.jsx)(f.HeadManagerContext.Provider,{value:{appDir:!0},children:(0,a.jsx)(y.ActionQueueContext.Provider,{value:e,children:(0,a.jsx)(T,{children:(0,a.jsx)(w,{})})})})}),n=window.__next_root_layout_missing_tags,r=!!(null==n?void 0:n.length),o={onRecoverableError:d.default};"__next_error__"===document.documentElement.id||r?i.default.createRoot(v,o).render(t):c.default.startTransition(()=>i.default.hydrateRoot(v,t,{...o,formState:R}))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},54278:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(19506),(0,n(75266).appBootstrap)(()=>{let{hydrate:e}=n(92304);n(12846),n(4707),e()}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},19506:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(65157);{let e=n.u;n.u=function(){for(var t=arguments.length,n=Array(t),r=0;r(l(function(){var e;let t=document.getElementsByName(u)[0];if(null==t?void 0:null==(e=t.shadowRoot)?void 0:e.childNodes[0])return t.shadowRoot.childNodes[0];{let e=document.createElement(u);e.style.cssText="position:absolute";let t=document.createElement("div");return t.ariaLive="assertive",t.id="__next-route-announcer__",t.role="alert",t.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal",e.attachShadow({mode:"open"}).appendChild(t),document.body.appendChild(e),t}}()),()=>{let e=document.getElementsByTagName(u)[0];(null==e?void 0:e.isConnected)&&document.body.removeChild(e)}),[]);let[a,i]=(0,r.useState)(""),c=(0,r.useRef)();return(0,r.useEffect)(()=>{let e="";if(document.title)e=document.title;else{let t=document.querySelector("h1");t&&(e=t.innerText||t.textContent||"")}void 0!==c.current&&c.current!==e&&i(e),c.current=e},[t]),n?(0,o.createPortal)(a,n):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6866:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ACTION:function(){return r},FLIGHT_PARAMETERS:function(){return i},NEXT_DID_POSTPONE_HEADER:function(){return s},NEXT_ROUTER_PREFETCH_HEADER:function(){return u},NEXT_ROUTER_STATE_TREE:function(){return o},NEXT_RSC_UNION_QUERY:function(){return c},NEXT_URL:function(){return l},RSC_CONTENT_TYPE_HEADER:function(){return a},RSC_HEADER:function(){return n}});let n="RSC",r="Next-Action",o="Next-Router-State-Tree",u="Next-Router-Prefetch",l="Next-Url",a="text/x-component",i=[[n],[o],[u]],c="_rsc",s="x-nextjs-postponed";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},12846:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{createEmptyCacheNode:function(){return C},default:function(){return I},getServerActionDispatcher:function(){return S},urlToUrlWithoutFlightMarker:function(){return M}});let r=n(53099),o=n(57437),u=r._(n(2265)),l=n(61956),a=n(24673),i=n(33456),c=n(79060),s=n(47744),f=n(61060),d=n(82952),p=n(86146),h=n(1634),y=n(6495),_=n(4123),v=n(39320),b=n(38137),g=n(6866),m=n(35076),R=n(11283),P=n(84541),j="undefined"==typeof window,O=j?null:new Map,E=null;function S(){return E}let w={};function M(e){let t=new URL(e,location.origin);if(t.searchParams.delete(g.NEXT_RSC_UNION_QUERY),t.pathname.endsWith(".txt")){let{pathname:e}=t,n=e.endsWith("/index.txt")?10:4;t.pathname=e.slice(0,-n)}return t}function T(e){return e.origin!==window.location.origin}function x(e){let{appRouterState:t,sync:n}=e;return(0,u.useInsertionEffect)(()=>{let{tree:e,pushRef:r,canonicalUrl:o}=t,u={...r.preserveCustomHistoryState?window.history.state:{},__NA:!0,__PRIVATE_NEXTJS_INTERNALS_TREE:e};r.pendingPush&&(0,i.createHrefFromUrl)(new URL(window.location.href))!==o?(r.pendingPush=!1,window.history.pushState(u,"",o)):window.history.replaceState(u,"",o),n(t)},[t,n]),null}function C(){return{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null}}function A(e){null==e&&(e={});let t=window.history.state,n=null==t?void 0:t.__NA;n&&(e.__NA=n);let r=null==t?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE;return r&&(e.__PRIVATE_NEXTJS_INTERNALS_TREE=r),e}function N(e){let{headCacheNode:t}=e,n=null!==t?t.head:null,r=null!==t?t.prefetchHead:null,o=null!==r?r:n;return(0,u.useDeferredValue)(n,o)}function D(e){let t,{buildId:n,initialHead:r,initialTree:i,urlParts:f,initialSeedData:g,couldBeIntercepted:S,assetPrefix:M,missingSlots:C}=e,D=(0,u.useMemo)(()=>(0,d.createInitialRouterState)({buildId:n,initialSeedData:g,urlParts:f,initialTree:i,initialParallelRoutes:O,location:j?null:window.location,initialHead:r,couldBeIntercepted:S}),[n,g,f,i,r,S]),[I,U,k]=(0,s.useReducerWithReduxDevtools)(D);(0,u.useEffect)(()=>{O=null},[]);let{canonicalUrl:F}=(0,s.useUnwrapState)(I),{searchParams:L,pathname:H}=(0,u.useMemo)(()=>{let e=new URL(F,"undefined"==typeof window?"http://n":window.location.href);return{searchParams:e.searchParams,pathname:(0,R.hasBasePath)(e.pathname)?(0,m.removeBasePath)(e.pathname):e.pathname}},[F]),G=(0,u.useCallback)(e=>{let{previousTree:t,serverResponse:n}=e;(0,u.startTransition)(()=>{U({type:a.ACTION_SERVER_PATCH,previousTree:t,serverResponse:n})})},[U]),$=(0,u.useCallback)((e,t,n)=>{let r=new URL((0,h.addBasePath)(e),location.href);return U({type:a.ACTION_NAVIGATE,url:r,isExternalUrl:T(r),locationSearch:location.search,shouldScroll:null==n||n,navigateType:t})},[U]);E=(0,u.useCallback)(e=>{(0,u.startTransition)(()=>{U({...e,type:a.ACTION_SERVER_ACTION})})},[U]);let z=(0,u.useMemo)(()=>({back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(e,t)=>{let n;if(!(0,p.isBot)(window.navigator.userAgent)){try{n=new URL((0,h.addBasePath)(e),window.location.href)}catch(t){throw Error("Cannot prefetch '"+e+"' because it cannot be converted to a URL.")}T(n)||(0,u.startTransition)(()=>{var e;U({type:a.ACTION_PREFETCH,url:n,kind:null!=(e=null==t?void 0:t.kind)?e:a.PrefetchKind.FULL})})}},replace:(e,t)=>{void 0===t&&(t={}),(0,u.startTransition)(()=>{var n;$(e,"replace",null==(n=t.scroll)||n)})},push:(e,t)=>{void 0===t&&(t={}),(0,u.startTransition)(()=>{var n;$(e,"push",null==(n=t.scroll)||n)})},refresh:()=>{(0,u.startTransition)(()=>{U({type:a.ACTION_REFRESH,origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}}),[U,$]);(0,u.useEffect)(()=>{window.next&&(window.next.router=z)},[z]),(0,u.useEffect)(()=>{function e(e){var t;e.persisted&&(null==(t=window.history.state)?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE)&&(w.pendingMpaPath=void 0,U({type:a.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE}))}return window.addEventListener("pageshow",e),()=>{window.removeEventListener("pageshow",e)}},[U]);let{pushRef:B}=(0,s.useUnwrapState)(I);if(B.mpaNavigation){if(w.pendingMpaPath!==F){let e=window.location;B.pendingPush?e.assign(F):e.replace(F),w.pendingMpaPath=F}(0,u.use)(b.unresolvedThenable)}(0,u.useEffect)(()=>{let e=window.history.pushState.bind(window.history),t=window.history.replaceState.bind(window.history),n=e=>{var t;let n=window.location.href,r=null==(t=window.history.state)?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE;(0,u.startTransition)(()=>{U({type:a.ACTION_RESTORE,url:new URL(null!=e?e:n,n),tree:r})})};window.history.pushState=function(t,r,o){return(null==t?void 0:t.__NA)||(null==t?void 0:t._N)||(t=A(t),o&&n(o)),e(t,r,o)},window.history.replaceState=function(e,r,o){return(null==e?void 0:e.__NA)||(null==e?void 0:e._N)||(e=A(e),o&&n(o)),t(e,r,o)};let r=e=>{let{state:t}=e;if(t){if(!t.__NA){window.location.reload();return}(0,u.startTransition)(()=>{U({type:a.ACTION_RESTORE,url:new URL(window.location.href),tree:t.__PRIVATE_NEXTJS_INTERNALS_TREE})})}};return window.addEventListener("popstate",r),()=>{window.history.pushState=e,window.history.replaceState=t,window.removeEventListener("popstate",r)}},[U]);let{cache:W,tree:K,nextUrl:V,focusAndScrollRef:Y}=(0,s.useUnwrapState)(I),X=(0,u.useMemo)(()=>(0,v.findHeadInCache)(W,K[1]),[W,K]),q=(0,u.useMemo)(()=>(function e(t,n){for(let r of(void 0===n&&(n={}),Object.values(t[1]))){let t=r[0],o=Array.isArray(t),u=o?t[1]:t;!u||u.startsWith(P.PAGE_SEGMENT_KEY)||(o&&("c"===t[2]||"oc"===t[2])?n[t[0]]=t[1].split("/"):o&&(n[t[0]]=t[1]),n=e(r,n))}return n})(K),[K]);if(null!==X){let[e,n]=X;t=(0,o.jsx)(N,{headCacheNode:e},n)}else t=null;let J=(0,o.jsxs)(_.RedirectBoundary,{children:[t,W.rsc,(0,o.jsx)(y.AppRouterAnnouncer,{tree:K})]});return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(x,{appRouterState:(0,s.useUnwrapState)(I),sync:k}),(0,o.jsx)(c.PathParamsContext.Provider,{value:q,children:(0,o.jsx)(c.PathnameContext.Provider,{value:H,children:(0,o.jsx)(c.SearchParamsContext.Provider,{value:L,children:(0,o.jsx)(l.GlobalLayoutRouterContext.Provider,{value:{buildId:n,changeByServerResponse:G,tree:K,focusAndScrollRef:Y,nextUrl:V},children:(0,o.jsx)(l.AppRouterContext.Provider,{value:z,children:(0,o.jsx)(l.LayoutRouterContext.Provider,{value:{childNodes:W.parallelRoutes,tree:K,url:F,loading:W.loading},children:J})})})})})})]})}function I(e){let{globalErrorComponent:t,...n}=e;return(0,o.jsx)(f.ErrorBoundary,{errorComponent:t,children:(0,o.jsx)(D,{...n})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},96149:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"bailoutToClientRendering",{enumerable:!0,get:function(){return u}});let r=n(18993),o=n(51845);function u(e){let t=o.staticGenerationAsyncStorage.getStore();if((null==t||!t.forceStatic)&&(null==t?void 0:t.isStaticGeneration))throw new r.BailoutToCSRError(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},19107:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ClientPageRoot",{enumerable:!0,get:function(){return u}});let r=n(57437),o=n(54535);function u(e){let{Component:t,props:n}=e;return n.searchParams=(0,o.createDynamicallyTrackedSearchParams)(n.searchParams||{}),(0,r.jsx)(t,{...n})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},61060:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ErrorBoundary:function(){return h},ErrorBoundaryHandler:function(){return f},GlobalError:function(){return d},default:function(){return p}});let r=n(47043),o=n(57437),u=r._(n(2265)),l=n(35475),a=n(89721),i=n(51845),c={error:{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"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function s(e){let{error:t}=e,n=i.staticGenerationAsyncStorage.getStore();if((null==n?void 0:n.isRevalidate)||(null==n?void 0:n.isStaticGeneration))throw console.error(t),t;return null}class f extends u.default.Component{static getDerivedStateFromError(e){if((0,a.isNextRouterError)(e))throw e;return{error:e}}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.error?{error:null,previousPathname:e.pathname}:{error:t.error,previousPathname:e.pathname}}render(){return this.state.error?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(s,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,(0,o.jsx)(this.props.errorComponent,{error:this.state.error,reset:this.reset})]}):this.props.children}constructor(e){super(e),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}}function d(e){let{error:t}=e,n=null==t?void 0:t.digest;return(0,o.jsxs)("html",{id:"__next_error__",children:[(0,o.jsx)("head",{}),(0,o.jsxs)("body",{children:[(0,o.jsx)(s,{error:t}),(0,o.jsx)("div",{style:c.error,children:(0,o.jsxs)("div",{children:[(0,o.jsx)("h2",{style:c.text,children:"Application error: a "+(n?"server":"client")+"-side exception has occurred (see the "+(n?"server logs":"browser console")+" for more information)."}),n?(0,o.jsx)("p",{style:c.text,children:"Digest: "+n}):null]})})]})]})}let p=d;function h(e){let{errorComponent:t,errorStyles:n,errorScripts:r,children:u}=e,a=(0,l.usePathname)();return t?(0,o.jsx)(f,{pathname:a,errorComponent:t,errorStyles:n,errorScripts:r,children:u}):(0,o.jsx)(o.Fragment,{children:u})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},46177:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{DynamicServerError:function(){return r},isDynamicServerError:function(){return o}});let n="DYNAMIC_SERVER_USAGE";class r extends Error{constructor(e){super("Dynamic server usage: "+e),this.description=e,this.digest=n}}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&"string"==typeof e.digest&&e.digest===n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},89721:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNextRouterError",{enumerable:!0,get:function(){return u}});let r=n(98200),o=n(88968);function u(e){return e&&e.digest&&((0,o.isRedirectError)(e)||(0,r.isNotFoundError)(e))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4707:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return E}});let r=n(47043),o=n(53099),u=n(57437),l=o._(n(2265)),a=r._(n(54887)),i=n(61956),c=n(44848),s=n(38137),f=n(61060),d=n(76015),p=n(7092),h=n(4123),y=n(80),_=n(73171),v=n(78505),b=n(28077),g=["bottom","height","left","right","top","width","x","y"];function m(e,t){let n=e.getBoundingClientRect();return n.top>=0&&n.top<=t}class R extends l.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:t}=this.props;if(e.apply){var n;if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>t.every((t,n)=>(0,d.matchSegment)(t,e[n]))))return;let r=null,o=e.hashFragment;if(o&&(r="top"===o?document.body:null!=(n=document.getElementById(o))?n:document.getElementsByName(o)[0]),r||(r="undefined"==typeof window?null:a.default.findDOMNode(this)),!(r instanceof Element))return;for(;!(r instanceof HTMLElement)||function(e){if(["sticky","fixed"].includes(getComputedStyle(e).position))return!0;let t=e.getBoundingClientRect();return g.every(e=>0===t[e])}(r);){if(null===r.nextElementSibling)return;r=r.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,p.handleSmoothScroll)(()=>{if(o){r.scrollIntoView();return}let e=document.documentElement,t=e.clientHeight;!m(r,t)&&(e.scrollTop=0,m(r,t)||r.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:e.onlyHashChange}),e.onlyHashChange=!1,r.focus()}}}}function P(e){let{segmentPath:t,children:n}=e,r=(0,l.useContext)(i.GlobalLayoutRouterContext);if(!r)throw Error("invariant global layout router not mounted");return(0,u.jsx)(R,{segmentPath:t,focusAndScrollRef:r.focusAndScrollRef,children:n})}function j(e){let{parallelRouterKey:t,url:n,childNodes:r,segmentPath:o,tree:a,cacheKey:f}=e,p=(0,l.useContext)(i.GlobalLayoutRouterContext);if(!p)throw Error("invariant global layout router not mounted");let{buildId:h,changeByServerResponse:y,tree:_}=p,v=r.get(f);if(void 0===v){let e={lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null};v=e,r.set(f,e)}let g=null!==v.prefetchRsc?v.prefetchRsc:v.rsc,m=(0,l.useDeferredValue)(v.rsc,g),R="object"==typeof m&&null!==m&&"function"==typeof m.then?(0,l.use)(m):m;if(!R){let e=v.lazyData;if(null===e){let t=function e(t,n){if(t){let[r,o]=t,u=2===t.length;if((0,d.matchSegment)(n[0],r)&&n[1].hasOwnProperty(o)){if(u){let t=e(void 0,n[1][o]);return[n[0],{...n[1],[o]:[t[0],t[1],t[2],"refetch"]}]}return[n[0],{...n[1],[o]:e(t.slice(2),n[1][o])}]}}return n}(["",...o],_),r=(0,b.hasInterceptionRouteInCurrentTree)(_);v.lazyData=e=(0,c.fetchServerResponse)(new URL(n,location.origin),t,r?p.nextUrl:null,h),v.lazyDataResolved=!1}let t=(0,l.use)(e);v.lazyDataResolved||(setTimeout(()=>{(0,l.startTransition)(()=>{y({previousTree:_,serverResponse:t})})}),v.lazyDataResolved=!0),(0,l.use)(s.unresolvedThenable)}return(0,u.jsx)(i.LayoutRouterContext.Provider,{value:{tree:a[1][t],childNodes:v.parallelRoutes,url:n,loading:v.loading},children:R})}function O(e){let{children:t,hasLoading:n,loading:r,loadingStyles:o,loadingScripts:a}=e;return n?(0,u.jsx)(l.Suspense,{fallback:(0,u.jsxs)(u.Fragment,{children:[o,a,r]}),children:t}):(0,u.jsx)(u.Fragment,{children:t})}function E(e){let{parallelRouterKey:t,segmentPath:n,error:r,errorStyles:o,errorScripts:a,templateStyles:c,templateScripts:s,template:d,notFound:p,notFoundStyles:b}=e,g=(0,l.useContext)(i.LayoutRouterContext);if(!g)throw Error("invariant expected layout router to be mounted");let{childNodes:m,tree:R,url:E,loading:S}=g,w=m.get(t);w||(w=new Map,m.set(t,w));let M=R[1][t][0],T=(0,_.getSegmentValue)(M),x=[M];return(0,u.jsx)(u.Fragment,{children:x.map(e=>{let l=(0,_.getSegmentValue)(e),g=(0,v.createRouterCacheKey)(e);return(0,u.jsxs)(i.TemplateContext.Provider,{value:(0,u.jsx)(P,{segmentPath:n,children:(0,u.jsx)(f.ErrorBoundary,{errorComponent:r,errorStyles:o,errorScripts:a,children:(0,u.jsx)(O,{hasLoading:!!S,loading:null==S?void 0:S[0],loadingStyles:null==S?void 0:S[1],loadingScripts:null==S?void 0:S[2],children:(0,u.jsx)(y.NotFoundBoundary,{notFound:p,notFoundStyles:b,children:(0,u.jsx)(h.RedirectBoundary,{children:(0,u.jsx)(j,{parallelRouterKey:t,url:E,tree:R,childNodes:w,segmentPath:n,cacheKey:g,isActive:T===l})})})})})}),children:[c,s,d]},(0,v.createRouterCacheKey)(e,!0))})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},76015:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{canSegmentBeOverridden:function(){return u},matchSegment:function(){return o}});let r=n(87417),o=(e,t)=>"string"==typeof e?"string"==typeof t&&e===t:"string"!=typeof t&&e[0]===t[0]&&e[1]===t[1],u=(e,t)=>{var n;return!Array.isArray(e)&&!!Array.isArray(t)&&(null==(n=(0,r.getSegmentParam)(e))?void 0:n.param)===t[0]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},35475:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ReadonlyURLSearchParams:function(){return i.ReadonlyURLSearchParams},RedirectType:function(){return i.RedirectType},ServerInsertedHTMLContext:function(){return c.ServerInsertedHTMLContext},notFound:function(){return i.notFound},permanentRedirect:function(){return i.permanentRedirect},redirect:function(){return i.redirect},useParams:function(){return p},usePathname:function(){return f},useRouter:function(){return d},useSearchParams:function(){return s},useSelectedLayoutSegment:function(){return y},useSelectedLayoutSegments:function(){return h},useServerInsertedHTML:function(){return c.useServerInsertedHTML}});let r=n(2265),o=n(61956),u=n(79060),l=n(73171),a=n(84541),i=n(52646),c=n(55501);function s(){let e=(0,r.useContext)(u.SearchParamsContext),t=(0,r.useMemo)(()=>e?new i.ReadonlyURLSearchParams(e):null,[e]);if("undefined"==typeof window){let{bailoutToClientRendering:e}=n(96149);e("useSearchParams()")}return t}function f(){return(0,r.useContext)(u.PathnameContext)}function d(){let e=(0,r.useContext)(o.AppRouterContext);if(null===e)throw Error("invariant expected app router to be mounted");return e}function p(){return(0,r.useContext)(u.PathParamsContext)}function h(e){void 0===e&&(e="children");let t=(0,r.useContext)(o.LayoutRouterContext);return t?function e(t,n,r,o){let u;if(void 0===r&&(r=!0),void 0===o&&(o=[]),r)u=t[1][n];else{var i;let e=t[1];u=null!=(i=e.children)?i:Object.values(e)[0]}if(!u)return o;let c=u[0],s=(0,l.getSegmentValue)(c);return!s||s.startsWith(a.PAGE_SEGMENT_KEY)?o:(o.push(s),e(u,n,!1,o))}(t.tree,e):null}function y(e){void 0===e&&(e="children");let t=h(e);if(!t||0===t.length)return null;let n="children"===e?t[0]:t[t.length-1];return n===a.DEFAULT_SEGMENT_KEY?null:n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},52646:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ReadonlyURLSearchParams:function(){return l},RedirectType:function(){return r.RedirectType},notFound:function(){return o.notFound},permanentRedirect:function(){return r.permanentRedirect},redirect:function(){return r.redirect}});let r=n(88968),o=n(98200);class u extends Error{constructor(){super("Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams")}}class l extends URLSearchParams{append(){throw new u}delete(){throw new u}set(){throw new u}sort(){throw new u}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},80:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NotFoundBoundary",{enumerable:!0,get:function(){return s}});let r=n(53099),o=n(57437),u=r._(n(2265)),l=n(35475),a=n(98200);n(31765);let i=n(61956);class c extends u.default.Component{componentDidCatch(){}static getDerivedStateFromError(e){if((0,a.isNotFoundError)(e))return{notFoundTriggered:!0};throw e}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.notFoundTriggered?{notFoundTriggered:!1,previousPathname:e.pathname}:{notFoundTriggered:t.notFoundTriggered,previousPathname:e.pathname}}render(){return this.state.notFoundTriggered?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("meta",{name:"robots",content:"noindex"}),!1,this.props.notFoundStyles,this.props.notFound]}):this.props.children}constructor(e){super(e),this.state={notFoundTriggered:!!e.asNotFound,previousPathname:e.pathname}}}function s(e){let{notFound:t,notFoundStyles:n,asNotFound:r,children:a}=e,s=(0,l.usePathname)(),f=(0,u.useContext)(i.MissingSlotContext);return t?(0,o.jsx)(c,{pathname:s,notFound:t,notFoundStyles:n,asNotFound:r,missingSlots:f,children:a}):(0,o.jsx)(o.Fragment,{children:a})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},98200:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{isNotFoundError:function(){return o},notFound:function(){return r}});let n="NEXT_NOT_FOUND";function r(){let e=Error(n);throw e.digest=n,e}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&e.digest===n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},29744:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PromiseQueue",{enumerable:!0,get:function(){return c}});let r=n(2522),o=n(90675);var u=o._("_maxConcurrency"),l=o._("_runningCount"),a=o._("_queue"),i=o._("_processNext");class c{enqueue(e){let t,n;let o=new Promise((e,r)=>{t=e,n=r}),u=async()=>{try{r._(this,l)[l]++;let n=await e();t(n)}catch(e){n(e)}finally{r._(this,l)[l]--,r._(this,i)[i]()}};return r._(this,a)[a].push({promiseFn:o,task:u}),r._(this,i)[i](),o}bump(e){let t=r._(this,a)[a].findIndex(t=>t.promiseFn===e);if(t>-1){let e=r._(this,a)[a].splice(t,1)[0];r._(this,a)[a].unshift(e),r._(this,i)[i](!0)}}constructor(e=5){Object.defineProperty(this,i,{value:s}),Object.defineProperty(this,u,{writable:!0,value:void 0}),Object.defineProperty(this,l,{writable:!0,value:void 0}),Object.defineProperty(this,a,{writable:!0,value:void 0}),r._(this,u)[u]=e,r._(this,l)[l]=0,r._(this,a)[a]=[]}}function s(e){if(void 0===e&&(e=!1),(r._(this,l)[l]0){var t;null==(t=r._(this,a)[a].shift())||t.task()}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4123:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{RedirectBoundary:function(){return s},RedirectErrorBoundary:function(){return c}});let r=n(53099),o=n(57437),u=r._(n(2265)),l=n(35475),a=n(88968);function i(e){let{redirect:t,reset:n,redirectType:r}=e,o=(0,l.useRouter)();return(0,u.useEffect)(()=>{u.default.startTransition(()=>{r===a.RedirectType.push?o.push(t,{}):o.replace(t,{}),n()})},[t,r,n,o]),null}class c extends u.default.Component{static getDerivedStateFromError(e){if((0,a.isRedirectError)(e))return{redirect:(0,a.getURLFromRedirectError)(e),redirectType:(0,a.getRedirectTypeFromError)(e)};throw e}render(){let{redirect:e,redirectType:t}=this.state;return null!==e&&null!==t?(0,o.jsx)(i,{redirect:e,redirectType:t,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(e){super(e),this.state={redirect:null,redirectType:null}}}function s(e){let{children:t}=e,n=(0,l.useRouter)();return(0,o.jsx)(c,{router:n,children:t})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5001:function(e,t){"use strict";var n,r;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RedirectStatusCode",{enumerable:!0,get:function(){return n}}),(r=n||(n={}))[r.SeeOther=303]="SeeOther",r[r.TemporaryRedirect=307]="TemporaryRedirect",r[r.PermanentRedirect=308]="PermanentRedirect",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},88968:function(e,t,n){"use strict";var r,o;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{RedirectType:function(){return r},getRedirectError:function(){return c},getRedirectStatusCodeFromError:function(){return y},getRedirectTypeFromError:function(){return h},getURLFromRedirectError:function(){return p},isRedirectError:function(){return d},permanentRedirect:function(){return f},redirect:function(){return s}});let u=n(20544),l=n(90295),a=n(5001),i="NEXT_REDIRECT";function c(e,t,n){void 0===n&&(n=a.RedirectStatusCode.TemporaryRedirect);let r=Error(i);r.digest=i+";"+t+";"+e+";"+n+";";let o=u.requestAsyncStorage.getStore();return o&&(r.mutableCookies=o.mutableCookies),r}function s(e,t){void 0===t&&(t="replace");let n=l.actionAsyncStorage.getStore();throw c(e,t,(null==n?void 0:n.isAction)?a.RedirectStatusCode.SeeOther:a.RedirectStatusCode.TemporaryRedirect)}function f(e,t){void 0===t&&(t="replace");let n=l.actionAsyncStorage.getStore();throw c(e,t,(null==n?void 0:n.isAction)?a.RedirectStatusCode.SeeOther:a.RedirectStatusCode.PermanentRedirect)}function d(e){if("object"!=typeof e||null===e||!("digest"in e)||"string"!=typeof e.digest)return!1;let[t,n,r,o]=e.digest.split(";",4),u=Number(o);return t===i&&("replace"===n||"push"===n)&&"string"==typeof r&&!isNaN(u)&&u in a.RedirectStatusCode}function p(e){return d(e)?e.digest.split(";",3)[2]:null}function h(e){if(!d(e))throw Error("Not a redirect error");return e.digest.split(";",2)[1]}function y(e){if(!d(e))throw Error("Not a redirect error");return Number(e.digest.split(";",4)[3])}(o=r||(r={})).push="push",o.replace="replace",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},36423:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let r=n(53099),o=n(57437),u=r._(n(2265)),l=n(61956);function a(){let e=(0,u.useContext)(l.TemplateContext);return(0,o.jsx)(o.Fragment,{children:e})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},20544:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getExpectedRequestStore:function(){return o},requestAsyncStorage:function(){return r.requestAsyncStorage}});let r=n(25575);function o(e){let t=r.requestAsyncStorage.getStore();if(t)return t;throw Error("`"+e+"` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},22356:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyFlightData",{enumerable:!0,get:function(){return u}});let r=n(27420),o=n(92576);function u(e,t,n,u){let[l,a,i]=n.slice(-3);if(null===a)return!1;if(3===n.length){let n=a[2],o=a[3];t.loading=o,t.rsc=n,t.prefetchRsc=null,(0,r.fillLazyItemsTillLeafWithHead)(t,e,l,a,i,u)}else t.rsc=e.rsc,t.prefetchRsc=e.prefetchRsc,t.parallelRoutes=new Map(e.parallelRoutes),t.loading=e.loading,(0,o.fillCacheWithNewSubTreeData)(t,e,n,u);return!0}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},81935:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return function e(t,n,r,a){let i;let[c,s,f,d,p]=n;if(1===t.length){let e=l(n,r,t);return(0,u.addRefreshMarkerToActiveParallelSegments)(e,a),e}let[h,y]=t;if(!(0,o.matchSegment)(h,c))return null;if(2===t.length)i=l(s[y],r,t);else if(null===(i=e(t.slice(2),s[y],r,a)))return null;let _=[t[0],{...s,[y]:i},f,d];return p&&(_[4]=!0),(0,u.addRefreshMarkerToActiveParallelSegments)(_,a),_}}});let r=n(84541),o=n(76015),u=n(50232);function l(e,t,n){let[u,a]=e,[i,c]=t;if(i===r.DEFAULT_SEGMENT_KEY&&u!==r.DEFAULT_SEGMENT_KEY)return e;if((0,o.matchSegment)(u,i)){let t={};for(let e in a)void 0!==c[e]?t[e]=l(a[e],c[e],n):t[e]=a[e];for(let e in c)t[e]||(t[e]=c[e]);let r=[u,t];return e[2]&&(r[2]=e[2]),e[3]&&(r[3]=e[3]),e[4]&&(r[4]=e[4]),r}return t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},65556:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"clearCacheNodeDataForSegmentPath",{enumerable:!0,get:function(){return function e(t,n,o){let u=o.length<=2,[l,a]=o,i=(0,r.createRouterCacheKey)(a),c=n.parallelRoutes.get(l),s=t.parallelRoutes.get(l);s&&s!==c||(s=new Map(c),t.parallelRoutes.set(l,s));let f=null==c?void 0:c.get(i),d=s.get(i);if(u){d&&d.lazyData&&d!==f||s.set(i,{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null});return}if(!d||!f){d||s.set(i,{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null});return}return d===f&&(d={lazyData:d.lazyData,rsc:d.rsc,prefetchRsc:d.prefetchRsc,head:d.head,prefetchHead:d.prefetchHead,parallelRoutes:new Map(d.parallelRoutes),lazyDataResolved:d.lazyDataResolved,loading:d.loading},s.set(i,d)),e(d,f,o.slice(2))}}});let r=n(78505);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5410:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{computeChangedPath:function(){return s},extractPathFromFlightRouterState:function(){return c}});let r=n(91182),o=n(84541),u=n(76015),l=e=>"/"===e[0]?e.slice(1):e,a=e=>"string"==typeof e?"children"===e?"":e:e[1];function i(e){return e.reduce((e,t)=>""===(t=l(t))||(0,o.isGroupSegment)(t)?e:e+"/"+t,"")||"/"}function c(e){var t;let n=Array.isArray(e[0])?e[0][1]:e[0];if(n===o.DEFAULT_SEGMENT_KEY||r.INTERCEPTION_ROUTE_MARKERS.some(e=>n.startsWith(e)))return;if(n.startsWith(o.PAGE_SEGMENT_KEY))return"";let u=[a(n)],l=null!=(t=e[1])?t:{},s=l.children?c(l.children):void 0;if(void 0!==s)u.push(s);else for(let[e,t]of Object.entries(l)){if("children"===e)continue;let n=c(t);void 0!==n&&u.push(n)}return i(u)}function s(e,t){let n=function e(t,n){let[o,l]=t,[i,s]=n,f=a(o),d=a(i);if(r.INTERCEPTION_ROUTE_MARKERS.some(e=>f.startsWith(e)||d.startsWith(e)))return"";if(!(0,u.matchSegment)(o,i)){var p;return null!=(p=c(n))?p:""}for(let t in l)if(s[t]){let n=e(l[t],s[t]);if(null!==n)return a(i)+"/"+n}return null}(e,t);return null==n||"/"===n?n:i(n.split("/"))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},33456:function(e,t){"use strict";function n(e,t){return void 0===t&&(t=!0),e.pathname+e.search+(t?e.hash:"")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createHrefFromUrl",{enumerable:!0,get:function(){return n}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},82952:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInitialRouterState",{enumerable:!0,get:function(){return c}});let r=n(33456),o=n(27420),u=n(5410),l=n(60305),a=n(24673),i=n(50232);function c(e){var t;let{buildId:n,initialTree:c,initialSeedData:s,urlParts:f,initialParallelRoutes:d,location:p,initialHead:h,couldBeIntercepted:y}=e,_=f.join("/"),v=!p,b={lazyData:null,rsc:s[2],prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:v?new Map:d,lazyDataResolved:!1,loading:s[3]},g=p?(0,r.createHrefFromUrl)(p):_;(0,i.addRefreshMarkerToActiveParallelSegments)(c,g);let m=new Map;(null===d||0===d.size)&&(0,o.fillLazyItemsTillLeafWithHead)(b,void 0,c,s,h);let R={buildId:n,tree:c,cache:b,prefetchCache:m,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:g,nextUrl:null!=(t=(0,u.extractPathFromFlightRouterState)(c)||(null==p?void 0:p.pathname))?t:null};if(p){let e=new URL(""+p.pathname+p.search,p.origin),t=[["",c,null,null]];(0,l.createPrefetchCacheEntryForInitialLoad)({url:e,kind:a.PrefetchKind.AUTO,data:[t,void 0,!1,y],tree:R.tree,prefetchCache:R.prefetchCache,nextUrl:R.nextUrl})}return R}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},78505:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRouterCacheKey",{enumerable:!0,get:function(){return o}});let r=n(84541);function o(e,t){return(void 0===t&&(t=!1),Array.isArray(e))?e[0]+"|"+e[1]+"|"+e[2]:t&&e.startsWith(r.PAGE_SEGMENT_KEY)?r.PAGE_SEGMENT_KEY:e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},44848:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fetchServerResponse",{enumerable:!0,get:function(){return f}});let r=n(6866),o=n(12846),u=n(83079),l=n(24673),a=n(37207),i=n(91311),{createFromFetch:c}=n(6671);function s(e){return[(0,o.urlToUrlWithoutFlightMarker)(e).toString(),void 0,!1,!1]}async function f(e,t,n,f,d){let p={[r.RSC_HEADER]:"1",[r.NEXT_ROUTER_STATE_TREE]:(0,i.prepareFlightRouterStateForRequest)(t)};d===l.PrefetchKind.AUTO&&(p[r.NEXT_ROUTER_PREFETCH_HEADER]="1"),n&&(p[r.NEXT_URL]=n);let h=(0,a.hexHash)([p[r.NEXT_ROUTER_PREFETCH_HEADER]||"0",p[r.NEXT_ROUTER_STATE_TREE],p[r.NEXT_URL]].join(","));try{var y;let t=new URL(e);t.pathname.endsWith("/")?t.pathname+="index.txt":t.pathname+=".txt",t.searchParams.set(r.NEXT_RSC_UNION_QUERY,h);let n=await fetch(t,{credentials:"same-origin",headers:p}),l=(0,o.urlToUrlWithoutFlightMarker)(n.url),a=n.redirected?l:void 0,i=n.headers.get("content-type")||"",d=!!n.headers.get(r.NEXT_DID_POSTPONE_HEADER),_=!!(null==(y=n.headers.get("vary"))?void 0:y.includes(r.NEXT_URL)),v=i===r.RSC_CONTENT_TYPE_HEADER;if(v||(v=i.startsWith("text/plain")),!v||!n.ok)return e.hash&&(l.hash=e.hash),s(l.toString());let[b,g]=await c(Promise.resolve(n),{callServer:u.callServer});if(f!==b)return s(n.url);return[g,a,d,_]}catch(t){return console.error("Failed to fetch RSC payload for "+e+". Falling back to browser navigation.",t),[e.toString(),void 0,!1,!1]}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},92576:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return function e(t,n,l,a){let i=l.length<=5,[c,s]=l,f=(0,u.createRouterCacheKey)(s),d=n.parallelRoutes.get(c);if(!d)return;let p=t.parallelRoutes.get(c);p&&p!==d||(p=new Map(d),t.parallelRoutes.set(c,p));let h=d.get(f),y=p.get(f);if(i){if(!y||!y.lazyData||y===h){let e=l[3];y={lazyData:null,rsc:e[2],prefetchRsc:null,head:null,prefetchHead:null,loading:e[3],parallelRoutes:h?new Map(h.parallelRoutes):new Map,lazyDataResolved:!1},h&&(0,r.invalidateCacheByRouterState)(y,h,l[2]),(0,o.fillLazyItemsTillLeafWithHead)(y,h,l[2],e,l[4],a),p.set(f,y)}return}y&&h&&(y===h&&(y={lazyData:y.lazyData,rsc:y.rsc,prefetchRsc:y.prefetchRsc,head:y.head,prefetchHead:y.prefetchHead,parallelRoutes:new Map(y.parallelRoutes),lazyDataResolved:!1,loading:y.loading},p.set(f,y)),e(y,h,l.slice(2),a))}}});let r=n(94377),o=n(27420),u=n(78505);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},27420:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return function e(t,n,u,l,a,i){if(0===Object.keys(u[1]).length){t.head=a;return}for(let c in u[1]){let s;let f=u[1][c],d=f[0],p=(0,r.createRouterCacheKey)(d),h=null!==l&&void 0!==l[1][c]?l[1][c]:null;if(n){let r=n.parallelRoutes.get(c);if(r){let n;let u=(null==i?void 0:i.kind)==="auto"&&i.status===o.PrefetchCacheEntryStatus.reusable,l=new Map(r),s=l.get(p);n=null!==h?{lazyData:null,rsc:h[2],prefetchRsc:null,head:null,prefetchHead:null,loading:h[3],parallelRoutes:new Map(null==s?void 0:s.parallelRoutes),lazyDataResolved:!1}:u&&s?{lazyData:s.lazyData,rsc:s.rsc,prefetchRsc:s.prefetchRsc,head:s.head,prefetchHead:s.prefetchHead,parallelRoutes:new Map(s.parallelRoutes),lazyDataResolved:s.lazyDataResolved,loading:s.loading}:{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map(null==s?void 0:s.parallelRoutes),lazyDataResolved:!1,loading:null},l.set(p,n),e(n,s,f,h||null,a,i),t.parallelRoutes.set(c,l);continue}}if(null!==h){let e=h[2],t=h[3];s={lazyData:null,rsc:e,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:t}}else s={lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null};let y=t.parallelRoutes.get(c);y?y.set(p,s):t.parallelRoutes.set(c,new Map([[p,s]])),e(s,void 0,f,h,a,i)}}}});let r=n(78505),o=n(24673);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},44510:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleMutable",{enumerable:!0,get:function(){return u}});let r=n(5410);function o(e){return void 0!==e}function u(e,t){var n,u,l;let a=null==(u=t.shouldScroll)||u,i=e.nextUrl;if(o(t.patchedTree)){let n=(0,r.computeChangedPath)(e.tree,t.patchedTree);n?i=n:i||(i=e.canonicalUrl)}return{buildId:e.buildId,canonicalUrl:o(t.canonicalUrl)?t.canonicalUrl===e.canonicalUrl?e.canonicalUrl:t.canonicalUrl:e.canonicalUrl,pushRef:{pendingPush:o(t.pendingPush)?t.pendingPush:e.pushRef.pendingPush,mpaNavigation:o(t.mpaNavigation)?t.mpaNavigation:e.pushRef.mpaNavigation,preserveCustomHistoryState:o(t.preserveCustomHistoryState)?t.preserveCustomHistoryState:e.pushRef.preserveCustomHistoryState},focusAndScrollRef:{apply:!!a&&(!!o(null==t?void 0:t.scrollableSegments)||e.focusAndScrollRef.apply),onlyHashChange:!!t.hashFragment&&e.canonicalUrl.split("#",1)[0]===(null==(n=t.canonicalUrl)?void 0:n.split("#",1)[0]),hashFragment:a?t.hashFragment&&""!==t.hashFragment?decodeURIComponent(t.hashFragment.slice(1)):e.focusAndScrollRef.hashFragment:null,segmentPaths:a?null!=(l=null==t?void 0:t.scrollableSegments)?l:e.focusAndScrollRef.segmentPaths:[]},cache:t.cache?t.cache:e.cache,prefetchCache:t.prefetchCache?t.prefetchCache:e.prefetchCache,tree:o(t.patchedTree)?t.patchedTree:e.tree,nextUrl:i}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},77831:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSegmentMismatch",{enumerable:!0,get:function(){return o}});let r=n(95967);function o(e,t,n){return(0,r.handleExternalUrl)(e,{},e.canonicalUrl,!0)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},77058:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheBelowFlightSegmentPath",{enumerable:!0,get:function(){return function e(t,n,o){let u=o.length<=2,[l,a]=o,i=(0,r.createRouterCacheKey)(a),c=n.parallelRoutes.get(l);if(!c)return;let s=t.parallelRoutes.get(l);if(s&&s!==c||(s=new Map(c),t.parallelRoutes.set(l,s)),u){s.delete(i);return}let f=c.get(i),d=s.get(i);d&&f&&(d===f&&(d={lazyData:d.lazyData,rsc:d.rsc,prefetchRsc:d.prefetchRsc,head:d.head,prefetchHead:d.prefetchHead,parallelRoutes:new Map(d.parallelRoutes),lazyDataResolved:d.lazyDataResolved},s.set(i,d)),e(d,f,o.slice(2)))}}});let r=n(78505);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},94377:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheByRouterState",{enumerable:!0,get:function(){return o}});let r=n(78505);function o(e,t,n){for(let o in n[1]){let u=n[1][o][0],l=(0,r.createRouterCacheKey)(u),a=t.parallelRoutes.get(o);if(a){let t=new Map(a);t.delete(l),e.parallelRoutes.set(o,t)}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},63237:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNavigatingToNewRootLayout",{enumerable:!0,get:function(){return function e(t,n){let r=t[0],o=n[0];if(Array.isArray(r)&&Array.isArray(o)){if(r[0]!==o[0]||r[2]!==o[2])return!0}else if(r!==o)return!0;if(t[4])return!n[4];if(n[4])return!0;let u=Object.values(t[1])[0],l=Object.values(n[1])[0];return!u||!l||e(u,l)}}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},56118:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{abortTask:function(){return c},listenForDynamicRequest:function(){return a},updateCacheNodeOnNavigation:function(){return function e(t,n,a,c,s){let f=n[1],d=a[1],p=c[1],h=t.parallelRoutes,y=new Map(h),_={},v=null;for(let t in d){let n;let a=d[t],c=f[t],b=h.get(t),g=p[t],m=a[0],R=(0,u.createRouterCacheKey)(m),P=void 0!==c?c[0]:void 0,j=void 0!==b?b.get(R):void 0;if(null!==(n=m===r.PAGE_SEGMENT_KEY?l(a,void 0!==g?g:null,s):m===r.DEFAULT_SEGMENT_KEY?void 0!==c?{route:c,node:null,children:null}:l(a,void 0!==g?g:null,s):void 0!==P&&(0,o.matchSegment)(m,P)&&void 0!==j&&void 0!==c?null!=g?e(j,c,a,g,s):function(e){let t=i(e,null,null);return{route:e,node:t,children:null}}(a):l(a,void 0!==g?g:null,s))){null===v&&(v=new Map),v.set(t,n);let e=n.node;if(null!==e){let n=new Map(b);n.set(R,e),y.set(t,n)}_[t]=n.route}else _[t]=a}if(null===v)return null;let b={lazyData:null,rsc:t.rsc,prefetchRsc:t.prefetchRsc,head:t.head,prefetchHead:t.prefetchHead,loading:t.loading,parallelRoutes:y,lazyDataResolved:!1};return{route:function(e,t){let n=[e[0],t];return 2 in e&&(n[2]=e[2]),3 in e&&(n[3]=e[3]),4 in e&&(n[4]=e[4]),n}(a,_),node:b,children:v}}},updateCacheNodeOnPopstateRestoration:function(){return function e(t,n){let r=n[1],o=t.parallelRoutes,l=new Map(o);for(let t in r){let n=r[t],a=n[0],i=(0,u.createRouterCacheKey)(a),c=o.get(t);if(void 0!==c){let r=c.get(i);if(void 0!==r){let o=e(r,n),u=new Map(c);u.set(i,o),l.set(t,u)}}}let a=t.rsc,i=d(a)&&"pending"===a.status;return{lazyData:null,rsc:a,head:t.head,prefetchHead:i?t.prefetchHead:null,prefetchRsc:i?t.prefetchRsc:null,loading:i?t.loading:null,parallelRoutes:l,lazyDataResolved:!1}}}});let r=n(84541),o=n(76015),u=n(78505);function l(e,t,n){let r=i(e,t,n);return{route:e,node:r,children:null}}function a(e,t){t.then(t=>{for(let n of t[0]){let t=n.slice(0,-3),r=n[n.length-3],l=n[n.length-2],a=n[n.length-1];"string"!=typeof t&&function(e,t,n,r,l){let a=e;for(let e=0;e{c(e,t)})}function i(e,t,n){let r=e[1],o=null!==t?t[1]:null,l=new Map;for(let e in r){let t=r[e],a=null!==o?o[e]:null,c=t[0],s=(0,u.createRouterCacheKey)(c),f=i(t,void 0===a?null:a,n),d=new Map;d.set(s,f),l.set(e,d)}let a=0===l.size,c=null!==t?t[2]:null,s=null!==t?t[3]:null;return{lazyData:null,parallelRoutes:l,prefetchRsc:void 0!==c?c:null,prefetchHead:a?n:null,loading:void 0!==s?s:null,rsc:p(),head:a?p():null,lazyDataResolved:!1}}function c(e,t){let n=e.node;if(null===n)return;let r=e.children;if(null===r)s(e.route,n,t);else for(let e of r.values())c(e,t);e.node=null}function s(e,t,n){let r=e[1],o=t.parallelRoutes;for(let e in r){let t=r[e],l=o.get(e);if(void 0===l)continue;let a=t[0],i=(0,u.createRouterCacheKey)(a),c=l.get(i);void 0!==c&&s(t,c,n)}let l=t.rsc;d(l)&&(null===n?l.resolve(null):l.reject(n));let a=t.head;d(a)&&a.resolve(null)}let f=Symbol();function d(e){return e&&e.tag===f}function p(){let e,t;let n=new Promise((n,r)=>{e=n,t=r});return n.status="pending",n.resolve=t=>{"pending"===n.status&&(n.status="fulfilled",n.value=t,e(t))},n.reject=e=>{"pending"===n.status&&(n.status="rejected",n.reason=e,t(e))},n.tag=f,n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},60305:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{createPrefetchCacheEntryForInitialLoad:function(){return c},getOrCreatePrefetchCacheEntry:function(){return i},prunePrefetchCache:function(){return f}});let r=n(33456),o=n(44848),u=n(24673),l=n(24819);function a(e,t){let n=(0,r.createHrefFromUrl)(e,!1);return t?t+"%"+n:n}function i(e){let t,{url:n,nextUrl:r,tree:o,buildId:l,prefetchCache:i,kind:c}=e,f=a(n,r),d=i.get(f);if(d)t=d;else{let e=a(n),r=i.get(e);r&&(t=r)}return t?(t.status=h(t),t.kind!==u.PrefetchKind.FULL&&c===u.PrefetchKind.FULL)?s({tree:o,url:n,buildId:l,nextUrl:r,prefetchCache:i,kind:null!=c?c:u.PrefetchKind.TEMPORARY}):(c&&t.kind===u.PrefetchKind.TEMPORARY&&(t.kind=c),t):s({tree:o,url:n,buildId:l,nextUrl:r,prefetchCache:i,kind:c||u.PrefetchKind.TEMPORARY})}function c(e){let{nextUrl:t,tree:n,prefetchCache:r,url:o,kind:l,data:i}=e,[,,,c]=i,s=c?a(o,t):a(o),f={treeAtTimeOfPrefetch:n,data:Promise.resolve(i),kind:l,prefetchTime:Date.now(),lastUsedTime:Date.now(),key:s,status:u.PrefetchCacheEntryStatus.fresh};return r.set(s,f),f}function s(e){let{url:t,kind:n,tree:r,nextUrl:i,buildId:c,prefetchCache:s}=e,f=a(t),d=l.prefetchQueue.enqueue(()=>(0,o.fetchServerResponse)(t,r,i,c,n).then(e=>{let[,,,n]=e;return n&&function(e){let{url:t,nextUrl:n,prefetchCache:r}=e,o=a(t),u=r.get(o);if(!u)return;let l=a(t,n);r.set(l,u),r.delete(o)}({url:t,nextUrl:i,prefetchCache:s}),e})),p={treeAtTimeOfPrefetch:r,data:d,kind:n,prefetchTime:Date.now(),lastUsedTime:null,key:f,status:u.PrefetchCacheEntryStatus.fresh};return s.set(f,p),p}function f(e){for(let[t,n]of e)h(n)===u.PrefetchCacheEntryStatus.expired&&e.delete(t)}let d=1e3*Number("30"),p=1e3*Number("300");function h(e){let{kind:t,prefetchTime:n,lastUsedTime:r}=e;return Date.now()<(null!=r?r:n)+d?r?u.PrefetchCacheEntryStatus.reusable:u.PrefetchCacheEntryStatus.fresh:"auto"===t&&Date.now(){let[n,f]=t,h=!1;if(E.lastUsedTime||(E.lastUsedTime=Date.now(),h=!0),"string"==typeof n)return _(e,R,n,O);if(document.getElementById("__next-page-redirect"))return _(e,R,j,O);let b=e.tree,g=e.cache,w=[];for(let t of n){let n=t.slice(0,-4),r=t.slice(-3)[0],c=["",...n],f=(0,u.applyRouterStatePatchToTree)(c,b,r,j);if(null===f&&(f=(0,u.applyRouterStatePatchToTree)(c,S,r,j)),null!==f){if((0,a.isNavigatingToNewRootLayout)(b,f))return _(e,R,j,O);let u=(0,d.createEmptyCacheNode)(),m=!1;for(let e of(E.status!==i.PrefetchCacheEntryStatus.stale||h?m=(0,s.applyFlightData)(g,u,t,E):(m=function(e,t,n,r){let o=!1;for(let u of(e.rsc=t.rsc,e.prefetchRsc=t.prefetchRsc,e.loading=t.loading,e.parallelRoutes=new Map(t.parallelRoutes),v(r).map(e=>[...n,...e])))(0,y.clearCacheNodeDataForSegmentPath)(e,t,u),o=!0;return o}(u,g,n,r),E.lastUsedTime=Date.now()),(0,l.shouldHardNavigate)(c,b)?(u.rsc=g.rsc,u.prefetchRsc=g.prefetchRsc,(0,o.invalidateCacheBelowFlightSegmentPath)(u,g,n),R.cache=u):m&&(R.cache=u,g=u),b=f,v(r))){let t=[...n,...e];t[t.length-1]!==p.DEFAULT_SEGMENT_KEY&&w.push(t)}}}return R.patchedTree=b,R.canonicalUrl=f?(0,r.createHrefFromUrl)(f):j,R.pendingPush=O,R.scrollableSegments=w,R.hashFragment=P,R.shouldScroll=m,(0,c.handleMutable)(e,R)},()=>e)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},24819:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{prefetchQueue:function(){return l},prefetchReducer:function(){return a}});let r=n(6866),o=n(29744),u=n(60305),l=new o.PromiseQueue(5);function a(e,t){(0,u.prunePrefetchCache)(e.prefetchCache);let{url:n}=t;return n.searchParams.delete(r.NEXT_RSC_UNION_QUERY),(0,u.getOrCreatePrefetchCacheEntry)({url:n,nextUrl:e.nextUrl,prefetchCache:e.prefetchCache,kind:t.kind,tree:e.tree,buildId:e.buildId}),e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},99601:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"refreshReducer",{enumerable:!0,get:function(){return h}});let r=n(44848),o=n(33456),u=n(81935),l=n(63237),a=n(95967),i=n(44510),c=n(27420),s=n(12846),f=n(77831),d=n(28077),p=n(50232);function h(e,t){let{origin:n}=t,h={},y=e.canonicalUrl,_=e.tree;h.preserveCustomHistoryState=!1;let v=(0,s.createEmptyCacheNode)(),b=(0,d.hasInterceptionRouteInCurrentTree)(e.tree);return v.lazyData=(0,r.fetchServerResponse)(new URL(y,n),[_[0],_[1],_[2],"refetch"],b?e.nextUrl:null,e.buildId),v.lazyData.then(async n=>{let[r,s]=n;if("string"==typeof r)return(0,a.handleExternalUrl)(e,h,r,e.pushRef.pendingPush);for(let n of(v.lazyData=null,r)){if(3!==n.length)return console.log("REFRESH FAILED"),e;let[r]=n,i=(0,u.applyRouterStatePatchToTree)([""],_,r,e.canonicalUrl);if(null===i)return(0,f.handleSegmentMismatch)(e,t,r);if((0,l.isNavigatingToNewRootLayout)(_,i))return(0,a.handleExternalUrl)(e,h,y,e.pushRef.pendingPush);let d=s?(0,o.createHrefFromUrl)(s):void 0;s&&(h.canonicalUrl=d);let[g,m]=n.slice(-2);if(null!==g){let e=g[2];v.rsc=e,v.prefetchRsc=null,(0,c.fillLazyItemsTillLeafWithHead)(v,void 0,r,g,m),h.prefetchCache=new Map}await (0,p.refreshInactiveParallelSegments)({state:e,updatedTree:i,updatedCache:v,includeNextUrl:b,canonicalUrl:h.canonicalUrl||e.canonicalUrl}),h.cache=v,h.patchedTree=i,h.canonicalUrl=y,_=i}return(0,i.handleMutable)(e,h)},()=>e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},77784:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"restoreReducer",{enumerable:!0,get:function(){return u}});let r=n(33456),o=n(5410);function u(e,t){var n;let{url:u,tree:l}=t,a=(0,r.createHrefFromUrl)(u),i=l||e.tree,c=e.cache;return{buildId:e.buildId,canonicalUrl:a,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:e.focusAndScrollRef,cache:c,prefetchCache:e.prefetchCache,tree:i,nextUrl:null!=(n=(0,o.extractPathFromFlightRouterState)(i))?n:u.pathname}}n(56118),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},13722:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverActionReducer",{enumerable:!0,get:function(){return m}});let r=n(83079),o=n(6866),u=n(1634),l=n(33456),a=n(95967),i=n(81935),c=n(63237),s=n(44510),f=n(27420),d=n(12846),p=n(28077),h=n(77831),y=n(50232),_=n(91311),{createFromFetch:v,encodeReply:b}=n(6671);async function g(e,t,n){let l,{actionId:a,actionArgs:i}=n,c=await b(i),s=await fetch("",{method:"POST",headers:{Accept:o.RSC_CONTENT_TYPE_HEADER,[o.ACTION]:a,[o.NEXT_ROUTER_STATE_TREE]:(0,_.prepareFlightRouterStateForRequest)(e.tree),...t?{[o.NEXT_URL]:t}:{}},body:c}),f=s.headers.get("x-action-redirect");try{let e=JSON.parse(s.headers.get("x-action-revalidated")||"[[],0,0]");l={paths:e[0]||[],tag:!!e[1],cookie:e[2]}}catch(e){l={paths:[],tag:!1,cookie:!1}}let d=f?new URL((0,u.addBasePath)(f),new URL(e.canonicalUrl,window.location.href)):void 0;if(s.headers.get("content-type")===o.RSC_CONTENT_TYPE_HEADER){let e=await v(Promise.resolve(s),{callServer:r.callServer});if(f){let[,t]=null!=e?e:[];return{actionFlightData:t,redirectLocation:d,revalidatedParts:l}}let[t,[,n]]=null!=e?e:[];return{actionResult:t,actionFlightData:n,redirectLocation:d,revalidatedParts:l}}return{redirectLocation:d,revalidatedParts:l}}function m(e,t){let{resolve:n,reject:r}=t,o={},u=e.canonicalUrl,_=e.tree;o.preserveCustomHistoryState=!1;let v=e.nextUrl&&(0,p.hasInterceptionRouteInCurrentTree)(e.tree)?e.nextUrl:null;return o.inFlightServerAction=g(e,v,t),o.inFlightServerAction.then(async r=>{let{actionResult:p,actionFlightData:b,redirectLocation:g}=r;if(g&&(e.pushRef.pendingPush=!0,o.pendingPush=!0),!b)return(n(p),g)?(0,a.handleExternalUrl)(e,o,g.href,e.pushRef.pendingPush):e;if("string"==typeof b)return(0,a.handleExternalUrl)(e,o,b,e.pushRef.pendingPush);if(o.inFlightServerAction=null,g){let e=(0,l.createHrefFromUrl)(g,!1);o.canonicalUrl=e}for(let n of b){if(3!==n.length)return console.log("SERVER ACTION APPLY FAILED"),e;let[r]=n,s=(0,i.applyRouterStatePatchToTree)([""],_,r,g?(0,l.createHrefFromUrl)(g):e.canonicalUrl);if(null===s)return(0,h.handleSegmentMismatch)(e,t,r);if((0,c.isNavigatingToNewRootLayout)(_,s))return(0,a.handleExternalUrl)(e,o,u,e.pushRef.pendingPush);let[p,b]=n.slice(-2),m=null!==p?p[2]:null;if(null!==m){let t=(0,d.createEmptyCacheNode)();t.rsc=m,t.prefetchRsc=null,(0,f.fillLazyItemsTillLeafWithHead)(t,void 0,r,p,b),await (0,y.refreshInactiveParallelSegments)({state:e,updatedTree:s,updatedCache:t,includeNextUrl:!!v,canonicalUrl:o.canonicalUrl||e.canonicalUrl}),o.cache=t,o.prefetchCache=new Map}o.patchedTree=s,_=s}return n(p),(0,s.handleMutable)(e,o)},t=>(r(t),e))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},68448:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverPatchReducer",{enumerable:!0,get:function(){return f}});let r=n(33456),o=n(81935),u=n(63237),l=n(95967),a=n(22356),i=n(44510),c=n(12846),s=n(77831);function f(e,t){let{serverResponse:n}=t,[f,d]=n,p={};if(p.preserveCustomHistoryState=!1,"string"==typeof f)return(0,l.handleExternalUrl)(e,p,f,e.pushRef.pendingPush);let h=e.tree,y=e.cache;for(let n of f){let i=n.slice(0,-4),[f]=n.slice(-3,-2),_=(0,o.applyRouterStatePatchToTree)(["",...i],h,f,e.canonicalUrl);if(null===_)return(0,s.handleSegmentMismatch)(e,t,f);if((0,u.isNavigatingToNewRootLayout)(h,_))return(0,l.handleExternalUrl)(e,p,e.canonicalUrl,e.pushRef.pendingPush);let v=d?(0,r.createHrefFromUrl)(d):void 0;v&&(p.canonicalUrl=v);let b=(0,c.createEmptyCacheNode)();(0,a.applyFlightData)(y,b,n),p.patchedTree=_,p.cache=b,y=b,h=_}return(0,i.handleMutable)(e,p)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},50232:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{addRefreshMarkerToActiveParallelSegments:function(){return function e(t,n){let[r,o,,l]=t;for(let a in r.includes(u.PAGE_SEGMENT_KEY)&&"refresh"!==l&&(t[2]=n,t[3]="refresh"),o)e(o[a],n)}},refreshInactiveParallelSegments:function(){return l}});let r=n(22356),o=n(44848),u=n(84541);async function l(e){let t=new Set;await a({...e,rootTree:e.updatedTree,fetchedSegments:t})}async function a(e){let{state:t,updatedTree:n,updatedCache:u,includeNextUrl:l,fetchedSegments:i,rootTree:c=n,canonicalUrl:s}=e,[,f,d,p]=n,h=[];if(d&&d!==s&&"refresh"===p&&!i.has(d)){i.add(d);let e=(0,o.fetchServerResponse)(new URL(d,location.origin),[c[0],c[1],c[2],"refetch"],l?t.nextUrl:null,t.buildId).then(e=>{let t=e[0];if("string"!=typeof t)for(let e of t)(0,r.applyFlightData)(u,u,e)});h.push(e)}for(let e in f){let n=a({state:t,updatedTree:f[e],updatedCache:u,includeNextUrl:l,fetchedSegments:i,rootTree:c,canonicalUrl:s});h.push(n)}await Promise.all(h)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},24673:function(e,t){"use strict";var n,r,o,u;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ACTION_FAST_REFRESH:function(){return f},ACTION_NAVIGATE:function(){return a},ACTION_PREFETCH:function(){return s},ACTION_REFRESH:function(){return l},ACTION_RESTORE:function(){return i},ACTION_SERVER_ACTION:function(){return d},ACTION_SERVER_PATCH:function(){return c},PrefetchCacheEntryStatus:function(){return r},PrefetchKind:function(){return n},isThenable:function(){return p}});let l="refresh",a="navigate",i="restore",c="server-patch",s="prefetch",f="fast-refresh",d="server-action";function p(e){return e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(o=n||(n={})).AUTO="auto",o.FULL="full",o.TEMPORARY="temporary",(u=r||(r={})).fresh="fresh",u.reusable="reusable",u.expired="expired",u.stale="stale",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},91450:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return f}});let r=n(24673),o=n(95967),u=n(68448),l=n(77784),a=n(99601),i=n(24819),c=n(44529),s=n(13722),f="undefined"==typeof window?function(e,t){return e}:function(e,t){switch(t.type){case r.ACTION_NAVIGATE:return(0,o.navigateReducer)(e,t);case r.ACTION_SERVER_PATCH:return(0,u.serverPatchReducer)(e,t);case r.ACTION_RESTORE:return(0,l.restoreReducer)(e,t);case r.ACTION_REFRESH:return(0,a.refreshReducer)(e,t);case r.ACTION_FAST_REFRESH:return(0,c.fastRefreshReducer)(e,t);case r.ACTION_PREFETCH:return(0,i.prefetchReducer)(e,t);case r.ACTION_SERVER_ACTION:return(0,s.serverActionReducer)(e,t);default:throw Error("Unknown action")}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},53728:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldHardNavigate",{enumerable:!0,get:function(){return function e(t,n){let[o,u]=n,[l,a]=t;return(0,r.matchSegment)(l,o)?!(t.length<=2)&&e(t.slice(2),u[a]):!!Array.isArray(l)}}});let r=n(76015);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},54535:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{createDynamicallyTrackedSearchParams:function(){return a},createUntrackedSearchParams:function(){return l}});let r=n(51845),o=n(86999),u=n(30650);function l(e){let t=r.staticGenerationAsyncStorage.getStore();return t&&t.forceStatic?{}:e}function a(e){let t=r.staticGenerationAsyncStorage.getStore();return t?t.forceStatic?{}:t.isStaticGeneration||t.dynamicShouldError?new Proxy({},{get:(e,n,r)=>("string"==typeof n&&(0,o.trackDynamicDataAccessed)(t,"searchParams."+n),u.ReflectAdapter.get(e,n,r)),has:(e,n)=>("string"==typeof n&&(0,o.trackDynamicDataAccessed)(t,"searchParams."+n),Reflect.has(e,n)),ownKeys:e=>((0,o.trackDynamicDataAccessed)(t,"searchParams"),Reflect.ownKeys(e))}):e:e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},51845:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationAsyncStorage",{enumerable:!0,get:function(){return r.staticGenerationAsyncStorage}});let r=n(20030);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},36864:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{StaticGenBailoutError:function(){return r},isStaticGenBailoutError:function(){return o}});let n="NEXT_STATIC_GEN_BAILOUT";class r extends Error{constructor(...e){super(...e),this.code=n}}function o(e){return"object"==typeof e&&null!==e&&"code"in e&&e.code===n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},38137:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"unresolvedThenable",{enumerable:!0,get:function(){return n}});let n={then:()=>{}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},47744:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{useReducerWithReduxDevtools:function(){return i},useUnwrapState:function(){return a}});let r=n(53099)._(n(2265)),o=n(24673),u=n(2103);function l(e){if(e instanceof Map){let t={};for(let[n,r]of e.entries()){if("function"==typeof r){t[n]="fn()";continue}if("object"==typeof r&&null!==r){if(r.$$typeof){t[n]=r.$$typeof.toString();continue}if(r._bundlerConfig){t[n]="FlightData";continue}}t[n]=l(r)}return t}if("object"==typeof e&&null!==e){let t={};for(let n in e){let r=e[n];if("function"==typeof r){t[n]="fn()";continue}if("object"==typeof r&&null!==r){if(r.$$typeof){t[n]=r.$$typeof.toString();continue}if(r.hasOwnProperty("_bundlerConfig")){t[n]="FlightData";continue}}t[n]=l(r)}return t}return Array.isArray(e)?e.map(l):e}function a(e){return(0,o.isThenable)(e)?(0,r.use)(e):e}let i="undefined"!=typeof window?function(e){let[t,n]=r.default.useState(e),o=(0,r.useContext)(u.ActionQueueContext);if(!o)throw Error("Invariant: Missing ActionQueueContext");let a=(0,r.useRef)(),i=(0,r.useRef)();return(0,r.useEffect)(()=>{if(!a.current&&!1!==i.current){if(void 0===i.current&&void 0===window.__REDUX_DEVTOOLS_EXTENSION__){i.current=!1;return}return a.current=window.__REDUX_DEVTOOLS_EXTENSION__.connect({instanceId:8e3,name:"next-router"}),a.current&&(a.current.init(l(e)),o&&(o.devToolsInstance=a.current)),()=>{a.current=void 0}}},[e,o]),[t,(0,r.useCallback)(t=>{o.state||(o.state=e),o.dispatch(t,n)},[o,e]),(0,r.useCallback)(e=>{a.current&&a.current.send({type:"RENDER_SYNC"},l(e))},[])]}:function(e){return[e,()=>{},()=>{}]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},91311:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prepareFlightRouterStateForRequest",{enumerable:!0,get:function(){return o}});let r=n(84541);function o(e,t){return t?encodeURIComponent(JSON.stringify(e)):encodeURIComponent(JSON.stringify(function e(t){let[n,o,,u,l]=t,a="string"==typeof n&&n.startsWith(r.PAGE_SEGMENT_KEY+"?")?r.PAGE_SEGMENT_KEY:n,i={};for(let[t,n]of Object.entries(o))i[t]=e(n);let c=[a,i,null,u&&"refresh"!==u?u:null];return void 0!==l&&(c[4]=l),c}(e)))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},11283:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return o}});let r=n(10580);function o(e){return(0,r.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},33068:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return u}});let r=n(26674),o=n(63381),u=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:n,hash:u}=(0,o.parsePath)(e);return""+(0,r.removeTrailingSlash)(t)+n+u};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},61404:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return o}});let r=n(18993);function o(e){let t="function"==typeof reportError?reportError:e=>{window.console.error(e)};(0,r.isBailoutToCSRError)(e)||t(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},35076:function(e,t,n){"use strict";function r(e){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return r}}),n(11283),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},12010:function(e,t){"use strict";function n(e,t){var n=e.length;for(e.push(t);0>>1,o=e[r];if(0>>1;ru(i,n))cu(s,i)?(e[r]=s,e[c]=n,r=c):(e[r]=i,e[a]=n,r=a);else if(cu(s,n))e[r]=s,e[c]=n,r=c;else break}}return t}function u(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}if(t.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var l,a=performance;t.unstable_now=function(){return a.now()}}else{var i=Date,c=i.now();t.unstable_now=function(){return i.now()-c}}var s=[],f=[],d=1,p=null,h=3,y=!1,_=!1,v=!1,b="function"==typeof setTimeout?setTimeout:null,g="function"==typeof clearTimeout?clearTimeout:null,m="undefined"!=typeof setImmediate?setImmediate:null;function R(e){for(var t=r(f);null!==t;){if(null===t.callback)o(f);else if(t.startTime<=e)o(f),t.sortIndex=t.expirationTime,n(s,t);else break;t=r(f)}}function P(e){if(v=!1,R(e),!_){if(null!==r(s))_=!0,C();else{var t=r(f);null!==t&&A(P,t.startTime-e)}}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var j=!1,O=-1,E=5,S=-1;function w(){return!(t.unstable_now()-Se&&w());){var a=p.callback;if("function"==typeof a){p.callback=null,h=p.priorityLevel;var i=a(p.expirationTime<=e);if(e=t.unstable_now(),"function"==typeof i){p.callback=i,R(e),n=!0;break t}p===r(s)&&o(s),R(e)}else o(s);p=r(s)}if(null!==p)n=!0;else{var c=r(f);null!==c&&A(P,c.startTime-e),n=!1}}break e}finally{p=null,h=u,y=!1}n=void 0}}finally{n?l():j=!1}}}if("function"==typeof m)l=function(){m(M)};else if("undefined"!=typeof MessageChannel){var T=new MessageChannel,x=T.port2;T.port1.onmessage=M,l=function(){x.postMessage(null)}}else l=function(){b(M,0)};function C(){j||(j=!0,l())}function A(e,n){O=b(function(){e(t.unstable_now())},n)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){_||y||(_=!0,C())},t.unstable_forceFrameRate=function(e){0>e||125l?(e.sortIndex=u,n(f,e),null===r(s)&&e===r(f)&&(v?(g(O),O=-1):v=!0,A(P,u-l))):(e.sortIndex=a,n(s,e),_||y||(_=!0,C())),e},t.unstable_shouldYield=w,t.unstable_wrapCallback=function(e){var t=h;return function(){var n=h;h=t;try{return e.apply(this,arguments)}finally{h=n}}}},71767:function(e,t,n){"use strict";e.exports=n(12010)},60934:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getPathname:function(){return r},isFullStringUrl:function(){return o},parseUrl:function(){return u}});let n="http://n";function r(e){return new URL(e,n).pathname}function o(e){return/https?:\/\//.test(e)}function u(e){let t;try{t=new URL(e,n)}catch{}return t}},86999:function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{Postpone:function(){return d},createPostponedAbortSignal:function(){return b},createPrerenderState:function(){return c},formatDynamicAPIAccesses:function(){return _},markCurrentScopeAsDynamic:function(){return s},trackDynamicDataAccessed:function(){return f},trackDynamicFetch:function(){return p},usedDynamicAPIs:function(){return y}});let o=(r=n(2265))&&r.__esModule?r:{default:r},u=n(46177),l=n(36864),a=n(60934),i="function"==typeof o.default.unstable_postpone;function c(e){return{isDebugSkeleton:e,dynamicAccesses:[]}}function s(e,t){let n=(0,a.getPathname)(e.urlPathname);if(!e.isUnstableCacheCallback){if(e.dynamicShouldError)throw new l.StaticGenBailoutError(`Route ${n} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${t}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);if(e.prerenderState)h(e.prerenderState,t,n);else if(e.revalidate=0,e.isStaticGeneration){let r=new u.DynamicServerError(`Route ${n} couldn't be rendered statically because it used ${t}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`);throw e.dynamicUsageDescription=t,e.dynamicUsageStack=r.stack,r}}}function f(e,t){let n=(0,a.getPathname)(e.urlPathname);if(e.isUnstableCacheCallback)throw Error(`Route ${n} used "${t}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${t}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`);if(e.dynamicShouldError)throw new l.StaticGenBailoutError(`Route ${n} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${t}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);if(e.prerenderState)h(e.prerenderState,t,n);else if(e.revalidate=0,e.isStaticGeneration){let r=new u.DynamicServerError(`Route ${n} couldn't be rendered statically because it used \`${t}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`);throw e.dynamicUsageDescription=t,e.dynamicUsageStack=r.stack,r}}function d({reason:e,prerenderState:t,pathname:n}){h(t,e,n)}function p(e,t){e.prerenderState&&h(e.prerenderState,t,e.urlPathname)}function h(e,t,n){v();let r=`Route ${n} needs to bail out of prerendering at this point because it used ${t}. React throws this special object to indicate where. It should not be caught by your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`;e.dynamicAccesses.push({stack:e.isDebugSkeleton?Error().stack:void 0,expression:t}),o.default.unstable_postpone(r)}function y(e){return e.dynamicAccesses.length>0}function _(e){return e.dynamicAccesses.filter(e=>"string"==typeof e.stack&&e.stack.length>0).map(({expression:e,stack:t})=>(t=t.split("\n").slice(4).filter(e=>!(e.includes("node_modules/next/")||e.includes(" ()")||e.includes(" (node:"))).join("\n"),`Dynamic API Usage Debug - ${e}: -${t}`))}function v(){if(!i)throw Error("Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js")}function b(e){v();let t=new AbortController;try{o.default.unstable_postpone(e)}catch(e){t.abort(e)}return t.signal}},87417:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentParam",{enumerable:!0,get:function(){return o}});let r=n(91182);function o(e){let t=r.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t));return(t&&(e=e.slice(t.length)),e.startsWith("[[...")&&e.endsWith("]]"))?{type:"optional-catchall",param:e.slice(5,-2)}:e.startsWith("[...")&&e.endsWith("]")?{type:t?"catchall-intercepted":"catchall",param:e.slice(4,-1)}:e.startsWith("[")&&e.endsWith("]")?{type:t?"dynamic-intercepted":"dynamic",param:e.slice(1,-1)}:null}},70647:function(e,t){"use strict";var n,r;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HMR_ACTIONS_SENT_TO_BROWSER",{enumerable:!0,get:function(){return n}}),(r=n||(n={})).ADDED_PAGE="addedPage",r.REMOVED_PAGE="removedPage",r.RELOAD_PAGE="reloadPage",r.SERVER_COMPONENT_CHANGES="serverComponentChanges",r.MIDDLEWARE_CHANGES="middlewareChanges",r.CLIENT_CHANGES="clientChanges",r.SERVER_ONLY_CHANGES="serverOnlyChanges",r.SYNC="sync",r.BUILT="built",r.BUILDING="building",r.DEV_PAGES_MANIFEST_UPDATE="devPagesManifestUpdate",r.TURBOPACK_MESSAGE="turbopack-message",r.SERVER_ERROR="serverError",r.TURBOPACK_CONNECTED="turbopack-connected"},91182:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return o},extractInterceptionRouteInformation:function(){return l},isInterceptionRouteAppPath:function(){return u}});let r=n(20926),o=["(..)(..)","(.)","(..)","(...)"];function u(e){return void 0!==e.split("/").find(e=>o.find(t=>e.startsWith(t)))}function l(e){let t,n,u;for(let r of e.split("/"))if(n=o.find(e=>r.startsWith(e))){[t,u]=e.split(n,2);break}if(!t||!n||!u)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,r.normalizeAppPath)(t),n){case"(.)":u="/"===t?`/${u}`:t+"/"+u;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);u=t.split("/").slice(0,-1).concat(u).join("/");break;case"(...)":u="/"+u;break;case"(..)(..)":let l=t.split("/");if(l.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);u=l.slice(0,-2).concat(u).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:u}}},30650:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ReflectAdapter",{enumerable:!0,get:function(){return n}});class n{static get(e,t,n){let r=Reflect.get(e,t,n);return"function"==typeof r?r.bind(e):r}static set(e,t,n,r){return Reflect.set(e,t,n,r)}static has(e,t){return Reflect.has(e,t)}static deleteProperty(e,t){return Reflect.deleteProperty(e,t)}}},61956:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{AppRouterContext:function(){return o},GlobalLayoutRouterContext:function(){return l},LayoutRouterContext:function(){return u},MissingSlotContext:function(){return i},TemplateContext:function(){return a}});let r=n(47043)._(n(2265)),o=r.default.createContext(null),u=r.default.createContext(null),l=r.default.createContext(null),a=r.default.createContext(null),i=r.default.createContext(new Set)},37207:function(e,t){"use strict";function n(e){let t=5381;for(let n=0;n>>0}function r(e){return n(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{djb2Hash:function(){return n},hexHash:function(){return r}})},48701:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HeadManagerContext",{enumerable:!0,get:function(){return r}});let r=n(47043)._(n(2265)).default.createContext({})},79060:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{PathParamsContext:function(){return l},PathnameContext:function(){return u},SearchParamsContext:function(){return o}});let r=n(2265),o=(0,r.createContext)(null),u=(0,r.createContext)(null),l=(0,r.createContext)(null)},18993:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{BailoutToCSRError:function(){return r},isBailoutToCSRError:function(){return o}});let n="BAILOUT_TO_CLIENT_SIDE_RENDERING";class r extends Error{constructor(e){super("Bail out to client-side rendering: "+e),this.reason=e,this.digest=n}}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&e.digest===n}},78162:function(e,t){"use strict";function n(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return n}})},2103:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ActionQueueContext:function(){return a},createMutableActionQueue:function(){return s}});let r=n(53099),o=n(24673),u=n(91450),l=r._(n(2265)),a=l.default.createContext(null);function i(e,t){null!==e.pending&&(e.pending=e.pending.next,null!==e.pending?c({actionQueue:e,action:e.pending,setState:t}):e.needsRefresh&&(e.needsRefresh=!1,e.dispatch({type:o.ACTION_REFRESH,origin:window.location.origin},t)))}async function c(e){let{actionQueue:t,action:n,setState:r}=e,u=t.state;if(!u)throw Error("Invariant: Router state not initialized");t.pending=n;let l=n.payload,a=t.action(u,l);function c(e){n.discarded||(t.state=e,t.devToolsInstance&&t.devToolsInstance.send(l,e),i(t,r),n.resolve(e))}(0,o.isThenable)(a)?a.then(c,e=>{i(t,r),n.reject(e)}):c(a)}function s(){let e={state:null,dispatch:(t,n)=>(function(e,t,n){let r={resolve:n,reject:()=>{}};if(t.type!==o.ACTION_RESTORE){let e=new Promise((e,t)=>{r={resolve:e,reject:t}});(0,l.startTransition)(()=>{n(e)})}let u={payload:t,next:null,resolve:r.resolve,reject:r.reject};null===e.pending?(e.last=u,c({actionQueue:e,action:u,setState:n})):t.type===o.ACTION_NAVIGATE||t.type===o.ACTION_RESTORE?(e.pending.discarded=!0,e.last=u,e.pending.payload.type===o.ACTION_SERVER_ACTION&&(e.needsRefresh=!0),c({actionQueue:e,action:u,setState:n})):(null!==e.last&&(e.last.next=u),e.last=u)})(e,t,n),action:async(e,t)=>{if(null===e)throw Error("Invariant: Router state not initialized");return(0,u.reducer)(e,t)},pending:null,last:null};return e}},68498:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return o}});let r=n(63381);function o(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:n,query:o,hash:u}=(0,r.parsePath)(e);return""+t+n+o+u}},20926:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{normalizeAppPath:function(){return u},normalizeRscURL:function(){return l}});let r=n(78162),o=n(84541);function u(e){return(0,r.ensureLeadingSlash)(e.split("/").reduce((e,t,n,r)=>!t||(0,o.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&n===r.length-1?e:e+"/"+t,""))}function l(e){return e.replace(/\.rsc($|\?)/,"$1")}},7092:function(e,t){"use strict";function n(e,t){if(void 0===t&&(t={}),t.onlyHashChange){e();return}let n=document.documentElement,r=n.style.scrollBehavior;n.style.scrollBehavior="auto",t.dontForceLayout||n.getClientRects(),e(),n.style.scrollBehavior=r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return n}})},86146:function(e,t){"use strict";function n(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isBot",{enumerable:!0,get:function(){return n}})},63381:function(e,t){"use strict";function n(e){let t=e.indexOf("#"),n=e.indexOf("?"),r=n>-1&&(t<0||n-1?{pathname:e.substring(0,r?n:t),query:r?e.substring(n,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return n}})},10580:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return o}});let r=n(63381);function o(e,t){if("string"!=typeof e)return!1;let{pathname:n}=(0,r.parsePath)(e);return n===t||n.startsWith(t+"/")}},26674:function(e,t){"use strict";function n(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return n}})},84541:function(e,t){"use strict";function n(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{DEFAULT_SEGMENT_KEY:function(){return o},PAGE_SEGMENT_KEY:function(){return r},isGroupSegment:function(){return n}});let r="__PAGE__",o="__DEFAULT__"},55501:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ServerInsertedHTMLContext:function(){return o},useServerInsertedHTML:function(){return u}});let r=n(53099)._(n(2265)),o=r.default.createContext(null);function u(e){let t=(0,r.useContext)(o);t&&t(e)}},31765:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return n}});let n=e=>{}},47149:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"actionAsyncStorage",{enumerable:!0,get:function(){return r}});let r=(0,n(54832).createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},54832:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createAsyncLocalStorage",{enumerable:!0,get:function(){return u}});let n=Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available");class r{disable(){throw n}getStore(){}run(){throw n}exit(){throw n}enterWith(){throw n}}let o=globalThis.AsyncLocalStorage;function u(){return o?new o:new r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},25575:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"requestAsyncStorage",{enumerable:!0,get:function(){return r}});let r=(0,n(54832).createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},20030:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationAsyncStorage",{enumerable:!0,get:function(){return r}});let r=(0,n(54832).createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},34040:function(e,t,n){"use strict";var r=n(54887);t.createRoot=r.createRoot,t.hydrateRoot=r.hydrateRoot},54887:function(e,t,n){"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=n(84417)},97950:function(e,t,n){"use strict";var r=n(54887),o={stream:!0},u=Object.prototype.hasOwnProperty,l=new Map;function a(e){var t=n(e);return"function"!=typeof t.then||"fulfilled"===t.status?null:(t.then(function(e){t.status="fulfilled",t.value=e},function(e){t.status="rejected",t.reason=e}),t)}function i(){}var c=new Map,s=n.u;n.u=function(e){var t=c.get(e);return void 0!==t?t:s(e)};var f=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher,d=Symbol.for("react.element"),p=Symbol.for("react.lazy"),h=Symbol.iterator,y=Array.isArray,_=Object.getPrototypeOf,v=Object.prototype,b=new WeakMap;function g(e,t,n,r){this.status=e,this.value=t,this.reason=n,this._response=r}function m(e){switch(e.status){case"resolved_model":w(e);break;case"resolved_module":M(e)}switch(e.status){case"fulfilled":return e.value;case"pending":case"blocked":case"cyclic":throw e;default:throw e.reason}}function R(e,t){for(var n=0;nh?(_=h,h=3,p++):(_=0,h=3);continue;case 2:44===(m=d[p++])?h=4:v=v<<4|(96d.length&&(m=-1)}var R=d.byteOffset+p;if(-11&&t.some(Array.isArray)?t.flat(e-1):t},Array.prototype.flatMap=function(e,t){return this.map(e,t).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(e){if("function"!=typeof e)return this.then(e,e);var t=this.constructor||Promise;return this.then(function(n){return t.resolve(e()).then(function(){return n})},function(n){return t.resolve(e()).then(function(){throw n})})}),Object.fromEntries||(Object.fromEntries=function(e){return Array.from(e).reduce(function(e,t){return e[t[0]]=t[1],e},{})}),Array.prototype.at||(Array.prototype.at=function(e){var t=Math.trunc(e)||0;if(t<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]}),Object.hasOwn||(Object.hasOwn=function(e,t){if(null==e)throw TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(e),t)}),"canParse"in URL||(URL.canParse=function(e,t){try{return new URL(e,t),!0}catch(e){return!1}})},1634:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return u}});let r=n(68498),o=n(33068);function u(e,t){return(0,o.normalizePathTrailingSlash)((0,r.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},75266:function(e,t){"use strict";function n(e){var t,n;t=self.__next_s,n=()=>{e()},t&&t.length?t.reduce((e,t)=>{let[n,r]=t;return e.then(()=>new Promise((e,t)=>{let o=document.createElement("script");if(r)for(let e in r)"children"!==e&&o.setAttribute(e,r[e]);n?(o.src=n,o.onload=()=>e(),o.onerror=t):r&&(o.innerHTML=r.children,setTimeout(e)),document.head.appendChild(o)}))},Promise.resolve()).catch(e=>{console.error(e)}).then(()=>{n()}):n()}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"appBootstrap",{enumerable:!0,get:function(){return n}}),window.next={version:"14.2.33",appDir:!0},("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},83079:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"callServer",{enumerable:!0,get:function(){return o}});let r=n(12846);async function o(e,t){let n=(0,r.getServerActionDispatcher)();if(!n)throw Error("Invariant: missing action dispatcher.");return new Promise((r,o)=>{n({actionId:e,actionArgs:t,resolve:r,reject:o})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},92304:function(e,t,n){"use strict";let r,o;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hydrate",{enumerable:!0,get:function(){return x}});let u=n(47043),l=n(53099),a=n(57437);n(91572);let i=u._(n(34040)),c=l._(n(2265)),s=n(6671),f=n(48701),d=u._(n(61404)),p=n(83079),h=n(89721),y=n(2103);n(70647);let _=window.console.error;window.console.error=function(){for(var e=arguments.length,t=Array(e),n=0;n{if((0,h.isNextRouterError)(e.error)){e.preventDefault();return}});let v=document,b=new TextEncoder,g=!1,m=!1,R=null;function P(e){if(0===e[0])r=[];else if(1===e[0]){if(!r)throw Error("Unexpected server data: missing bootstrap script.");o?o.enqueue(b.encode(e[1])):r.push(e[1])}else 2===e[0]&&(R=e[1])}let j=function(){o&&!m&&(o.close(),m=!0,r=void 0),g=!0};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",j,!1):j();let O=self.__next_f=self.__next_f||[];O.forEach(P),O.push=P;let E=new ReadableStream({start(e){r&&(r.forEach(t=>{e.enqueue(b.encode(t))}),g&&!m&&(e.close(),m=!0,r=void 0)),o=e}}),S=(0,s.createFromReadableStream)(E,{callServer:p.callServer});function w(){return(0,c.use)(S)}let M=c.default.StrictMode;function T(e){let{children:t}=e;return t}function x(){let e=(0,y.createMutableActionQueue)(),t=(0,a.jsx)(M,{children:(0,a.jsx)(f.HeadManagerContext.Provider,{value:{appDir:!0},children:(0,a.jsx)(y.ActionQueueContext.Provider,{value:e,children:(0,a.jsx)(T,{children:(0,a.jsx)(w,{})})})})}),n=window.__next_root_layout_missing_tags,r=!!(null==n?void 0:n.length),o={onRecoverableError:d.default};"__next_error__"===document.documentElement.id||r?i.default.createRoot(v,o).render(t):c.default.startTransition(()=>i.default.hydrateRoot(v,t,{...o,formState:R}))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},54278:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(19506),(0,n(75266).appBootstrap)(()=>{let{hydrate:e}=n(92304);n(12846),n(4707),e()}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},19506:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(65157);{let e=n.u;n.u=function(){for(var t=arguments.length,n=Array(t),r=0;r(l(function(){var e;let t=document.getElementsByName(u)[0];if(null==t?void 0:null==(e=t.shadowRoot)?void 0:e.childNodes[0])return t.shadowRoot.childNodes[0];{let e=document.createElement(u);e.style.cssText="position:absolute";let t=document.createElement("div");return t.ariaLive="assertive",t.id="__next-route-announcer__",t.role="alert",t.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal",e.attachShadow({mode:"open"}).appendChild(t),document.body.appendChild(e),t}}()),()=>{let e=document.getElementsByTagName(u)[0];(null==e?void 0:e.isConnected)&&document.body.removeChild(e)}),[]);let[a,i]=(0,r.useState)(""),c=(0,r.useRef)();return(0,r.useEffect)(()=>{let e="";if(document.title)e=document.title;else{let t=document.querySelector("h1");t&&(e=t.innerText||t.textContent||"")}void 0!==c.current&&c.current!==e&&i(e),c.current=e},[t]),n?(0,o.createPortal)(a,n):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6866:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ACTION:function(){return r},FLIGHT_PARAMETERS:function(){return i},NEXT_DID_POSTPONE_HEADER:function(){return s},NEXT_ROUTER_PREFETCH_HEADER:function(){return u},NEXT_ROUTER_STATE_TREE:function(){return o},NEXT_RSC_UNION_QUERY:function(){return c},NEXT_URL:function(){return l},RSC_CONTENT_TYPE_HEADER:function(){return a},RSC_HEADER:function(){return n}});let n="RSC",r="Next-Action",o="Next-Router-State-Tree",u="Next-Router-Prefetch",l="Next-Url",a="text/x-component",i=[[n],[o],[u]],c="_rsc",s="x-nextjs-postponed";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},12846:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{createEmptyCacheNode:function(){return C},default:function(){return I},getServerActionDispatcher:function(){return S},urlToUrlWithoutFlightMarker:function(){return M}});let r=n(53099),o=n(57437),u=r._(n(2265)),l=n(61956),a=n(24673),i=n(33456),c=n(79060),s=n(47744),f=n(61060),d=n(82952),p=n(86146),h=n(1634),y=n(6495),_=n(4123),v=n(39320),b=n(38137),g=n(6866),m=n(35076),R=n(11283),P=n(84541),j="undefined"==typeof window,O=j?null:new Map,E=null;function S(){return E}let w={};function M(e){let t=new URL(e,location.origin);if(t.searchParams.delete(g.NEXT_RSC_UNION_QUERY),t.pathname.endsWith(".txt")){let{pathname:e}=t,n=e.endsWith("/index.txt")?10:4;t.pathname=e.slice(0,-n)}return t}function T(e){return e.origin!==window.location.origin}function x(e){let{appRouterState:t,sync:n}=e;return(0,u.useInsertionEffect)(()=>{let{tree:e,pushRef:r,canonicalUrl:o}=t,u={...r.preserveCustomHistoryState?window.history.state:{},__NA:!0,__PRIVATE_NEXTJS_INTERNALS_TREE:e};r.pendingPush&&(0,i.createHrefFromUrl)(new URL(window.location.href))!==o?(r.pendingPush=!1,window.history.pushState(u,"",o)):window.history.replaceState(u,"",o),n(t)},[t,n]),null}function C(){return{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null}}function A(e){null==e&&(e={});let t=window.history.state,n=null==t?void 0:t.__NA;n&&(e.__NA=n);let r=null==t?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE;return r&&(e.__PRIVATE_NEXTJS_INTERNALS_TREE=r),e}function N(e){let{headCacheNode:t}=e,n=null!==t?t.head:null,r=null!==t?t.prefetchHead:null,o=null!==r?r:n;return(0,u.useDeferredValue)(n,o)}function D(e){let t,{buildId:n,initialHead:r,initialTree:i,urlParts:f,initialSeedData:g,couldBeIntercepted:S,assetPrefix:M,missingSlots:C}=e,D=(0,u.useMemo)(()=>(0,d.createInitialRouterState)({buildId:n,initialSeedData:g,urlParts:f,initialTree:i,initialParallelRoutes:O,location:j?null:window.location,initialHead:r,couldBeIntercepted:S}),[n,g,f,i,r,S]),[I,U,k]=(0,s.useReducerWithReduxDevtools)(D);(0,u.useEffect)(()=>{O=null},[]);let{canonicalUrl:F}=(0,s.useUnwrapState)(I),{searchParams:L,pathname:H}=(0,u.useMemo)(()=>{let e=new URL(F,"undefined"==typeof window?"http://n":window.location.href);return{searchParams:e.searchParams,pathname:(0,R.hasBasePath)(e.pathname)?(0,m.removeBasePath)(e.pathname):e.pathname}},[F]),G=(0,u.useCallback)(e=>{let{previousTree:t,serverResponse:n}=e;(0,u.startTransition)(()=>{U({type:a.ACTION_SERVER_PATCH,previousTree:t,serverResponse:n})})},[U]),$=(0,u.useCallback)((e,t,n)=>{let r=new URL((0,h.addBasePath)(e),location.href);return U({type:a.ACTION_NAVIGATE,url:r,isExternalUrl:T(r),locationSearch:location.search,shouldScroll:null==n||n,navigateType:t})},[U]);E=(0,u.useCallback)(e=>{(0,u.startTransition)(()=>{U({...e,type:a.ACTION_SERVER_ACTION})})},[U]);let z=(0,u.useMemo)(()=>({back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(e,t)=>{let n;if(!(0,p.isBot)(window.navigator.userAgent)){try{n=new URL((0,h.addBasePath)(e),window.location.href)}catch(t){throw Error("Cannot prefetch '"+e+"' because it cannot be converted to a URL.")}T(n)||(0,u.startTransition)(()=>{var e;U({type:a.ACTION_PREFETCH,url:n,kind:null!=(e=null==t?void 0:t.kind)?e:a.PrefetchKind.FULL})})}},replace:(e,t)=>{void 0===t&&(t={}),(0,u.startTransition)(()=>{var n;$(e,"replace",null==(n=t.scroll)||n)})},push:(e,t)=>{void 0===t&&(t={}),(0,u.startTransition)(()=>{var n;$(e,"push",null==(n=t.scroll)||n)})},refresh:()=>{(0,u.startTransition)(()=>{U({type:a.ACTION_REFRESH,origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}}),[U,$]);(0,u.useEffect)(()=>{window.next&&(window.next.router=z)},[z]),(0,u.useEffect)(()=>{function e(e){var t;e.persisted&&(null==(t=window.history.state)?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE)&&(w.pendingMpaPath=void 0,U({type:a.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE}))}return window.addEventListener("pageshow",e),()=>{window.removeEventListener("pageshow",e)}},[U]);let{pushRef:B}=(0,s.useUnwrapState)(I);if(B.mpaNavigation){if(w.pendingMpaPath!==F){let e=window.location;B.pendingPush?e.assign(F):e.replace(F),w.pendingMpaPath=F}(0,u.use)(b.unresolvedThenable)}(0,u.useEffect)(()=>{let e=window.history.pushState.bind(window.history),t=window.history.replaceState.bind(window.history),n=e=>{var t;let n=window.location.href,r=null==(t=window.history.state)?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE;(0,u.startTransition)(()=>{U({type:a.ACTION_RESTORE,url:new URL(null!=e?e:n,n),tree:r})})};window.history.pushState=function(t,r,o){return(null==t?void 0:t.__NA)||(null==t?void 0:t._N)||(t=A(t),o&&n(o)),e(t,r,o)},window.history.replaceState=function(e,r,o){return(null==e?void 0:e.__NA)||(null==e?void 0:e._N)||(e=A(e),o&&n(o)),t(e,r,o)};let r=e=>{let{state:t}=e;if(t){if(!t.__NA){window.location.reload();return}(0,u.startTransition)(()=>{U({type:a.ACTION_RESTORE,url:new URL(window.location.href),tree:t.__PRIVATE_NEXTJS_INTERNALS_TREE})})}};return window.addEventListener("popstate",r),()=>{window.history.pushState=e,window.history.replaceState=t,window.removeEventListener("popstate",r)}},[U]);let{cache:W,tree:K,nextUrl:V,focusAndScrollRef:Y}=(0,s.useUnwrapState)(I),X=(0,u.useMemo)(()=>(0,v.findHeadInCache)(W,K[1]),[W,K]),q=(0,u.useMemo)(()=>(function e(t,n){for(let r of(void 0===n&&(n={}),Object.values(t[1]))){let t=r[0],o=Array.isArray(t),u=o?t[1]:t;!u||u.startsWith(P.PAGE_SEGMENT_KEY)||(o&&("c"===t[2]||"oc"===t[2])?n[t[0]]=t[1].split("/"):o&&(n[t[0]]=t[1]),n=e(r,n))}return n})(K),[K]);if(null!==X){let[e,n]=X;t=(0,o.jsx)(N,{headCacheNode:e},n)}else t=null;let J=(0,o.jsxs)(_.RedirectBoundary,{children:[t,W.rsc,(0,o.jsx)(y.AppRouterAnnouncer,{tree:K})]});return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(x,{appRouterState:(0,s.useUnwrapState)(I),sync:k}),(0,o.jsx)(c.PathParamsContext.Provider,{value:q,children:(0,o.jsx)(c.PathnameContext.Provider,{value:H,children:(0,o.jsx)(c.SearchParamsContext.Provider,{value:L,children:(0,o.jsx)(l.GlobalLayoutRouterContext.Provider,{value:{buildId:n,changeByServerResponse:G,tree:K,focusAndScrollRef:Y,nextUrl:V},children:(0,o.jsx)(l.AppRouterContext.Provider,{value:z,children:(0,o.jsx)(l.LayoutRouterContext.Provider,{value:{childNodes:W.parallelRoutes,tree:K,url:F,loading:W.loading},children:J})})})})})})]})}function I(e){let{globalErrorComponent:t,...n}=e;return(0,o.jsx)(f.ErrorBoundary,{errorComponent:t,children:(0,o.jsx)(D,{...n})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},96149:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"bailoutToClientRendering",{enumerable:!0,get:function(){return u}});let r=n(18993),o=n(51845);function u(e){let t=o.staticGenerationAsyncStorage.getStore();if((null==t||!t.forceStatic)&&(null==t?void 0:t.isStaticGeneration))throw new r.BailoutToCSRError(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},19107:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ClientPageRoot",{enumerable:!0,get:function(){return u}});let r=n(57437),o=n(54535);function u(e){let{Component:t,props:n}=e;return n.searchParams=(0,o.createDynamicallyTrackedSearchParams)(n.searchParams||{}),(0,r.jsx)(t,{...n})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},61060:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ErrorBoundary:function(){return h},ErrorBoundaryHandler:function(){return f},GlobalError:function(){return d},default:function(){return p}});let r=n(47043),o=n(57437),u=r._(n(2265)),l=n(35475),a=n(89721),i=n(51845),c={error:{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"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function s(e){let{error:t}=e,n=i.staticGenerationAsyncStorage.getStore();if((null==n?void 0:n.isRevalidate)||(null==n?void 0:n.isStaticGeneration))throw console.error(t),t;return null}class f extends u.default.Component{static getDerivedStateFromError(e){if((0,a.isNextRouterError)(e))throw e;return{error:e}}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.error?{error:null,previousPathname:e.pathname}:{error:t.error,previousPathname:e.pathname}}render(){return this.state.error?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(s,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,(0,o.jsx)(this.props.errorComponent,{error:this.state.error,reset:this.reset})]}):this.props.children}constructor(e){super(e),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}}function d(e){let{error:t}=e,n=null==t?void 0:t.digest;return(0,o.jsxs)("html",{id:"__next_error__",children:[(0,o.jsx)("head",{}),(0,o.jsxs)("body",{children:[(0,o.jsx)(s,{error:t}),(0,o.jsx)("div",{style:c.error,children:(0,o.jsxs)("div",{children:[(0,o.jsx)("h2",{style:c.text,children:"Application error: a "+(n?"server":"client")+"-side exception has occurred (see the "+(n?"server logs":"browser console")+" for more information)."}),n?(0,o.jsx)("p",{style:c.text,children:"Digest: "+n}):null]})})]})]})}let p=d;function h(e){let{errorComponent:t,errorStyles:n,errorScripts:r,children:u}=e,a=(0,l.usePathname)();return t?(0,o.jsx)(f,{pathname:a,errorComponent:t,errorStyles:n,errorScripts:r,children:u}):(0,o.jsx)(o.Fragment,{children:u})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},46177:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{DynamicServerError:function(){return r},isDynamicServerError:function(){return o}});let n="DYNAMIC_SERVER_USAGE";class r extends Error{constructor(e){super("Dynamic server usage: "+e),this.description=e,this.digest=n}}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&"string"==typeof e.digest&&e.digest===n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},89721:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNextRouterError",{enumerable:!0,get:function(){return u}});let r=n(98200),o=n(88968);function u(e){return e&&e.digest&&((0,o.isRedirectError)(e)||(0,r.isNotFoundError)(e))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4707:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return E}});let r=n(47043),o=n(53099),u=n(57437),l=o._(n(2265)),a=r._(n(54887)),i=n(61956),c=n(44848),s=n(38137),f=n(61060),d=n(76015),p=n(7092),h=n(4123),y=n(80),_=n(73171),v=n(78505),b=n(28077),g=["bottom","height","left","right","top","width","x","y"];function m(e,t){let n=e.getBoundingClientRect();return n.top>=0&&n.top<=t}class R extends l.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:t}=this.props;if(e.apply){var n;if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>t.every((t,n)=>(0,d.matchSegment)(t,e[n]))))return;let r=null,o=e.hashFragment;if(o&&(r="top"===o?document.body:null!=(n=document.getElementById(o))?n:document.getElementsByName(o)[0]),r||(r="undefined"==typeof window?null:a.default.findDOMNode(this)),!(r instanceof Element))return;for(;!(r instanceof HTMLElement)||function(e){if(["sticky","fixed"].includes(getComputedStyle(e).position))return!0;let t=e.getBoundingClientRect();return g.every(e=>0===t[e])}(r);){if(null===r.nextElementSibling)return;r=r.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,p.handleSmoothScroll)(()=>{if(o){r.scrollIntoView();return}let e=document.documentElement,t=e.clientHeight;!m(r,t)&&(e.scrollTop=0,m(r,t)||r.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:e.onlyHashChange}),e.onlyHashChange=!1,r.focus()}}}}function P(e){let{segmentPath:t,children:n}=e,r=(0,l.useContext)(i.GlobalLayoutRouterContext);if(!r)throw Error("invariant global layout router not mounted");return(0,u.jsx)(R,{segmentPath:t,focusAndScrollRef:r.focusAndScrollRef,children:n})}function j(e){let{parallelRouterKey:t,url:n,childNodes:r,segmentPath:o,tree:a,cacheKey:f}=e,p=(0,l.useContext)(i.GlobalLayoutRouterContext);if(!p)throw Error("invariant global layout router not mounted");let{buildId:h,changeByServerResponse:y,tree:_}=p,v=r.get(f);if(void 0===v){let e={lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null};v=e,r.set(f,e)}let g=null!==v.prefetchRsc?v.prefetchRsc:v.rsc,m=(0,l.useDeferredValue)(v.rsc,g),R="object"==typeof m&&null!==m&&"function"==typeof m.then?(0,l.use)(m):m;if(!R){let e=v.lazyData;if(null===e){let t=function e(t,n){if(t){let[r,o]=t,u=2===t.length;if((0,d.matchSegment)(n[0],r)&&n[1].hasOwnProperty(o)){if(u){let t=e(void 0,n[1][o]);return[n[0],{...n[1],[o]:[t[0],t[1],t[2],"refetch"]}]}return[n[0],{...n[1],[o]:e(t.slice(2),n[1][o])}]}}return n}(["",...o],_),r=(0,b.hasInterceptionRouteInCurrentTree)(_);v.lazyData=e=(0,c.fetchServerResponse)(new URL(n,location.origin),t,r?p.nextUrl:null,h),v.lazyDataResolved=!1}let t=(0,l.use)(e);v.lazyDataResolved||(setTimeout(()=>{(0,l.startTransition)(()=>{y({previousTree:_,serverResponse:t})})}),v.lazyDataResolved=!0),(0,l.use)(s.unresolvedThenable)}return(0,u.jsx)(i.LayoutRouterContext.Provider,{value:{tree:a[1][t],childNodes:v.parallelRoutes,url:n,loading:v.loading},children:R})}function O(e){let{children:t,hasLoading:n,loading:r,loadingStyles:o,loadingScripts:a}=e;return n?(0,u.jsx)(l.Suspense,{fallback:(0,u.jsxs)(u.Fragment,{children:[o,a,r]}),children:t}):(0,u.jsx)(u.Fragment,{children:t})}function E(e){let{parallelRouterKey:t,segmentPath:n,error:r,errorStyles:o,errorScripts:a,templateStyles:c,templateScripts:s,template:d,notFound:p,notFoundStyles:b}=e,g=(0,l.useContext)(i.LayoutRouterContext);if(!g)throw Error("invariant expected layout router to be mounted");let{childNodes:m,tree:R,url:E,loading:S}=g,w=m.get(t);w||(w=new Map,m.set(t,w));let M=R[1][t][0],T=(0,_.getSegmentValue)(M),x=[M];return(0,u.jsx)(u.Fragment,{children:x.map(e=>{let l=(0,_.getSegmentValue)(e),g=(0,v.createRouterCacheKey)(e);return(0,u.jsxs)(i.TemplateContext.Provider,{value:(0,u.jsx)(P,{segmentPath:n,children:(0,u.jsx)(f.ErrorBoundary,{errorComponent:r,errorStyles:o,errorScripts:a,children:(0,u.jsx)(O,{hasLoading:!!S,loading:null==S?void 0:S[0],loadingStyles:null==S?void 0:S[1],loadingScripts:null==S?void 0:S[2],children:(0,u.jsx)(y.NotFoundBoundary,{notFound:p,notFoundStyles:b,children:(0,u.jsx)(h.RedirectBoundary,{children:(0,u.jsx)(j,{parallelRouterKey:t,url:E,tree:R,childNodes:w,segmentPath:n,cacheKey:g,isActive:T===l})})})})})}),children:[c,s,d]},(0,v.createRouterCacheKey)(e,!0))})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},76015:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{canSegmentBeOverridden:function(){return u},matchSegment:function(){return o}});let r=n(87417),o=(e,t)=>"string"==typeof e?"string"==typeof t&&e===t:"string"!=typeof t&&e[0]===t[0]&&e[1]===t[1],u=(e,t)=>{var n;return!Array.isArray(e)&&!!Array.isArray(t)&&(null==(n=(0,r.getSegmentParam)(e))?void 0:n.param)===t[0]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},35475:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ReadonlyURLSearchParams:function(){return i.ReadonlyURLSearchParams},RedirectType:function(){return i.RedirectType},ServerInsertedHTMLContext:function(){return c.ServerInsertedHTMLContext},notFound:function(){return i.notFound},permanentRedirect:function(){return i.permanentRedirect},redirect:function(){return i.redirect},useParams:function(){return p},usePathname:function(){return f},useRouter:function(){return d},useSearchParams:function(){return s},useSelectedLayoutSegment:function(){return y},useSelectedLayoutSegments:function(){return h},useServerInsertedHTML:function(){return c.useServerInsertedHTML}});let r=n(2265),o=n(61956),u=n(79060),l=n(73171),a=n(84541),i=n(52646),c=n(55501);function s(){let e=(0,r.useContext)(u.SearchParamsContext),t=(0,r.useMemo)(()=>e?new i.ReadonlyURLSearchParams(e):null,[e]);if("undefined"==typeof window){let{bailoutToClientRendering:e}=n(96149);e("useSearchParams()")}return t}function f(){return(0,r.useContext)(u.PathnameContext)}function d(){let e=(0,r.useContext)(o.AppRouterContext);if(null===e)throw Error("invariant expected app router to be mounted");return e}function p(){return(0,r.useContext)(u.PathParamsContext)}function h(e){void 0===e&&(e="children");let t=(0,r.useContext)(o.LayoutRouterContext);return t?function e(t,n,r,o){let u;if(void 0===r&&(r=!0),void 0===o&&(o=[]),r)u=t[1][n];else{var i;let e=t[1];u=null!=(i=e.children)?i:Object.values(e)[0]}if(!u)return o;let c=u[0],s=(0,l.getSegmentValue)(c);return!s||s.startsWith(a.PAGE_SEGMENT_KEY)?o:(o.push(s),e(u,n,!1,o))}(t.tree,e):null}function y(e){void 0===e&&(e="children");let t=h(e);if(!t||0===t.length)return null;let n="children"===e?t[0]:t[t.length-1];return n===a.DEFAULT_SEGMENT_KEY?null:n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},52646:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ReadonlyURLSearchParams:function(){return l},RedirectType:function(){return r.RedirectType},notFound:function(){return o.notFound},permanentRedirect:function(){return r.permanentRedirect},redirect:function(){return r.redirect}});let r=n(88968),o=n(98200);class u extends Error{constructor(){super("Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams")}}class l extends URLSearchParams{append(){throw new u}delete(){throw new u}set(){throw new u}sort(){throw new u}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},80:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NotFoundBoundary",{enumerable:!0,get:function(){return s}});let r=n(53099),o=n(57437),u=r._(n(2265)),l=n(35475),a=n(98200);n(31765);let i=n(61956);class c extends u.default.Component{componentDidCatch(){}static getDerivedStateFromError(e){if((0,a.isNotFoundError)(e))return{notFoundTriggered:!0};throw e}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.notFoundTriggered?{notFoundTriggered:!1,previousPathname:e.pathname}:{notFoundTriggered:t.notFoundTriggered,previousPathname:e.pathname}}render(){return this.state.notFoundTriggered?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("meta",{name:"robots",content:"noindex"}),!1,this.props.notFoundStyles,this.props.notFound]}):this.props.children}constructor(e){super(e),this.state={notFoundTriggered:!!e.asNotFound,previousPathname:e.pathname}}}function s(e){let{notFound:t,notFoundStyles:n,asNotFound:r,children:a}=e,s=(0,l.usePathname)(),f=(0,u.useContext)(i.MissingSlotContext);return t?(0,o.jsx)(c,{pathname:s,notFound:t,notFoundStyles:n,asNotFound:r,missingSlots:f,children:a}):(0,o.jsx)(o.Fragment,{children:a})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},98200:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{isNotFoundError:function(){return o},notFound:function(){return r}});let n="NEXT_NOT_FOUND";function r(){let e=Error(n);throw e.digest=n,e}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&e.digest===n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},29744:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PromiseQueue",{enumerable:!0,get:function(){return c}});let r=n(2522),o=n(90675);var u=o._("_maxConcurrency"),l=o._("_runningCount"),a=o._("_queue"),i=o._("_processNext");class c{enqueue(e){let t,n;let o=new Promise((e,r)=>{t=e,n=r}),u=async()=>{try{r._(this,l)[l]++;let n=await e();t(n)}catch(e){n(e)}finally{r._(this,l)[l]--,r._(this,i)[i]()}};return r._(this,a)[a].push({promiseFn:o,task:u}),r._(this,i)[i](),o}bump(e){let t=r._(this,a)[a].findIndex(t=>t.promiseFn===e);if(t>-1){let e=r._(this,a)[a].splice(t,1)[0];r._(this,a)[a].unshift(e),r._(this,i)[i](!0)}}constructor(e=5){Object.defineProperty(this,i,{value:s}),Object.defineProperty(this,u,{writable:!0,value:void 0}),Object.defineProperty(this,l,{writable:!0,value:void 0}),Object.defineProperty(this,a,{writable:!0,value:void 0}),r._(this,u)[u]=e,r._(this,l)[l]=0,r._(this,a)[a]=[]}}function s(e){if(void 0===e&&(e=!1),(r._(this,l)[l]0){var t;null==(t=r._(this,a)[a].shift())||t.task()}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4123:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{RedirectBoundary:function(){return s},RedirectErrorBoundary:function(){return c}});let r=n(53099),o=n(57437),u=r._(n(2265)),l=n(35475),a=n(88968);function i(e){let{redirect:t,reset:n,redirectType:r}=e,o=(0,l.useRouter)();return(0,u.useEffect)(()=>{u.default.startTransition(()=>{r===a.RedirectType.push?o.push(t,{}):o.replace(t,{}),n()})},[t,r,n,o]),null}class c extends u.default.Component{static getDerivedStateFromError(e){if((0,a.isRedirectError)(e))return{redirect:(0,a.getURLFromRedirectError)(e),redirectType:(0,a.getRedirectTypeFromError)(e)};throw e}render(){let{redirect:e,redirectType:t}=this.state;return null!==e&&null!==t?(0,o.jsx)(i,{redirect:e,redirectType:t,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(e){super(e),this.state={redirect:null,redirectType:null}}}function s(e){let{children:t}=e,n=(0,l.useRouter)();return(0,o.jsx)(c,{router:n,children:t})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5001:function(e,t){"use strict";var n,r;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RedirectStatusCode",{enumerable:!0,get:function(){return n}}),(r=n||(n={}))[r.SeeOther=303]="SeeOther",r[r.TemporaryRedirect=307]="TemporaryRedirect",r[r.PermanentRedirect=308]="PermanentRedirect",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},88968:function(e,t,n){"use strict";var r,o;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{RedirectType:function(){return r},getRedirectError:function(){return c},getRedirectStatusCodeFromError:function(){return y},getRedirectTypeFromError:function(){return h},getURLFromRedirectError:function(){return p},isRedirectError:function(){return d},permanentRedirect:function(){return f},redirect:function(){return s}});let u=n(20544),l=n(90295),a=n(5001),i="NEXT_REDIRECT";function c(e,t,n){void 0===n&&(n=a.RedirectStatusCode.TemporaryRedirect);let r=Error(i);r.digest=i+";"+t+";"+e+";"+n+";";let o=u.requestAsyncStorage.getStore();return o&&(r.mutableCookies=o.mutableCookies),r}function s(e,t){void 0===t&&(t="replace");let n=l.actionAsyncStorage.getStore();throw c(e,t,(null==n?void 0:n.isAction)?a.RedirectStatusCode.SeeOther:a.RedirectStatusCode.TemporaryRedirect)}function f(e,t){void 0===t&&(t="replace");let n=l.actionAsyncStorage.getStore();throw c(e,t,(null==n?void 0:n.isAction)?a.RedirectStatusCode.SeeOther:a.RedirectStatusCode.PermanentRedirect)}function d(e){if("object"!=typeof e||null===e||!("digest"in e)||"string"!=typeof e.digest)return!1;let[t,n,r,o]=e.digest.split(";",4),u=Number(o);return t===i&&("replace"===n||"push"===n)&&"string"==typeof r&&!isNaN(u)&&u in a.RedirectStatusCode}function p(e){return d(e)?e.digest.split(";",3)[2]:null}function h(e){if(!d(e))throw Error("Not a redirect error");return e.digest.split(";",2)[1]}function y(e){if(!d(e))throw Error("Not a redirect error");return Number(e.digest.split(";",4)[3])}(o=r||(r={})).push="push",o.replace="replace",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},36423:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let r=n(53099),o=n(57437),u=r._(n(2265)),l=n(61956);function a(){let e=(0,u.useContext)(l.TemplateContext);return(0,o.jsx)(o.Fragment,{children:e})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},20544:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getExpectedRequestStore:function(){return o},requestAsyncStorage:function(){return r.requestAsyncStorage}});let r=n(25575);function o(e){let t=r.requestAsyncStorage.getStore();if(t)return t;throw Error("`"+e+"` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},22356:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyFlightData",{enumerable:!0,get:function(){return u}});let r=n(27420),o=n(92576);function u(e,t,n,u){let[l,a,i]=n.slice(-3);if(null===a)return!1;if(3===n.length){let n=a[2],o=a[3];t.loading=o,t.rsc=n,t.prefetchRsc=null,(0,r.fillLazyItemsTillLeafWithHead)(t,e,l,a,i,u)}else t.rsc=e.rsc,t.prefetchRsc=e.prefetchRsc,t.parallelRoutes=new Map(e.parallelRoutes),t.loading=e.loading,(0,o.fillCacheWithNewSubTreeData)(t,e,n,u);return!0}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},81935:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return function e(t,n,r,a){let i;let[c,s,f,d,p]=n;if(1===t.length){let e=l(n,r,t);return(0,u.addRefreshMarkerToActiveParallelSegments)(e,a),e}let[h,y]=t;if(!(0,o.matchSegment)(h,c))return null;if(2===t.length)i=l(s[y],r,t);else if(null===(i=e(t.slice(2),s[y],r,a)))return null;let _=[t[0],{...s,[y]:i},f,d];return p&&(_[4]=!0),(0,u.addRefreshMarkerToActiveParallelSegments)(_,a),_}}});let r=n(84541),o=n(76015),u=n(50232);function l(e,t,n){let[u,a]=e,[i,c]=t;if(i===r.DEFAULT_SEGMENT_KEY&&u!==r.DEFAULT_SEGMENT_KEY)return e;if((0,o.matchSegment)(u,i)){let t={};for(let e in a)void 0!==c[e]?t[e]=l(a[e],c[e],n):t[e]=a[e];for(let e in c)t[e]||(t[e]=c[e]);let r=[u,t];return e[2]&&(r[2]=e[2]),e[3]&&(r[3]=e[3]),e[4]&&(r[4]=e[4]),r}return t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},65556:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"clearCacheNodeDataForSegmentPath",{enumerable:!0,get:function(){return function e(t,n,o){let u=o.length<=2,[l,a]=o,i=(0,r.createRouterCacheKey)(a),c=n.parallelRoutes.get(l),s=t.parallelRoutes.get(l);s&&s!==c||(s=new Map(c),t.parallelRoutes.set(l,s));let f=null==c?void 0:c.get(i),d=s.get(i);if(u){d&&d.lazyData&&d!==f||s.set(i,{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null});return}if(!d||!f){d||s.set(i,{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null});return}return d===f&&(d={lazyData:d.lazyData,rsc:d.rsc,prefetchRsc:d.prefetchRsc,head:d.head,prefetchHead:d.prefetchHead,parallelRoutes:new Map(d.parallelRoutes),lazyDataResolved:d.lazyDataResolved,loading:d.loading},s.set(i,d)),e(d,f,o.slice(2))}}});let r=n(78505);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5410:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{computeChangedPath:function(){return s},extractPathFromFlightRouterState:function(){return c}});let r=n(91182),o=n(84541),u=n(76015),l=e=>"/"===e[0]?e.slice(1):e,a=e=>"string"==typeof e?"children"===e?"":e:e[1];function i(e){return e.reduce((e,t)=>""===(t=l(t))||(0,o.isGroupSegment)(t)?e:e+"/"+t,"")||"/"}function c(e){var t;let n=Array.isArray(e[0])?e[0][1]:e[0];if(n===o.DEFAULT_SEGMENT_KEY||r.INTERCEPTION_ROUTE_MARKERS.some(e=>n.startsWith(e)))return;if(n.startsWith(o.PAGE_SEGMENT_KEY))return"";let u=[a(n)],l=null!=(t=e[1])?t:{},s=l.children?c(l.children):void 0;if(void 0!==s)u.push(s);else for(let[e,t]of Object.entries(l)){if("children"===e)continue;let n=c(t);void 0!==n&&u.push(n)}return i(u)}function s(e,t){let n=function e(t,n){let[o,l]=t,[i,s]=n,f=a(o),d=a(i);if(r.INTERCEPTION_ROUTE_MARKERS.some(e=>f.startsWith(e)||d.startsWith(e)))return"";if(!(0,u.matchSegment)(o,i)){var p;return null!=(p=c(n))?p:""}for(let t in l)if(s[t]){let n=e(l[t],s[t]);if(null!==n)return a(i)+"/"+n}return null}(e,t);return null==n||"/"===n?n:i(n.split("/"))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},33456:function(e,t){"use strict";function n(e,t){return void 0===t&&(t=!0),e.pathname+e.search+(t?e.hash:"")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createHrefFromUrl",{enumerable:!0,get:function(){return n}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},82952:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInitialRouterState",{enumerable:!0,get:function(){return c}});let r=n(33456),o=n(27420),u=n(5410),l=n(60305),a=n(24673),i=n(50232);function c(e){var t;let{buildId:n,initialTree:c,initialSeedData:s,urlParts:f,initialParallelRoutes:d,location:p,initialHead:h,couldBeIntercepted:y}=e,_=f.join("/"),v=!p,b={lazyData:null,rsc:s[2],prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:v?new Map:d,lazyDataResolved:!1,loading:s[3]},g=p?(0,r.createHrefFromUrl)(p):_;(0,i.addRefreshMarkerToActiveParallelSegments)(c,g);let m=new Map;(null===d||0===d.size)&&(0,o.fillLazyItemsTillLeafWithHead)(b,void 0,c,s,h);let R={buildId:n,tree:c,cache:b,prefetchCache:m,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:g,nextUrl:null!=(t=(0,u.extractPathFromFlightRouterState)(c)||(null==p?void 0:p.pathname))?t:null};if(p){let e=new URL(""+p.pathname+p.search,p.origin),t=[["",c,null,null]];(0,l.createPrefetchCacheEntryForInitialLoad)({url:e,kind:a.PrefetchKind.AUTO,data:[t,void 0,!1,y],tree:R.tree,prefetchCache:R.prefetchCache,nextUrl:R.nextUrl})}return R}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},78505:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRouterCacheKey",{enumerable:!0,get:function(){return o}});let r=n(84541);function o(e,t){return(void 0===t&&(t=!1),Array.isArray(e))?e[0]+"|"+e[1]+"|"+e[2]:t&&e.startsWith(r.PAGE_SEGMENT_KEY)?r.PAGE_SEGMENT_KEY:e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},44848:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fetchServerResponse",{enumerable:!0,get:function(){return f}});let r=n(6866),o=n(12846),u=n(83079),l=n(24673),a=n(37207),i=n(91311),{createFromFetch:c}=n(6671);function s(e){return[(0,o.urlToUrlWithoutFlightMarker)(e).toString(),void 0,!1,!1]}async function f(e,t,n,f,d){let p={[r.RSC_HEADER]:"1",[r.NEXT_ROUTER_STATE_TREE]:(0,i.prepareFlightRouterStateForRequest)(t)};d===l.PrefetchKind.AUTO&&(p[r.NEXT_ROUTER_PREFETCH_HEADER]="1"),n&&(p[r.NEXT_URL]=n);let h=(0,a.hexHash)([p[r.NEXT_ROUTER_PREFETCH_HEADER]||"0",p[r.NEXT_ROUTER_STATE_TREE],p[r.NEXT_URL]].join(","));try{var y;let t=new URL(e);t.pathname.endsWith("/")?t.pathname+="index.txt":t.pathname+=".txt",t.searchParams.set(r.NEXT_RSC_UNION_QUERY,h);let n=await fetch(t,{credentials:"same-origin",headers:p}),l=(0,o.urlToUrlWithoutFlightMarker)(n.url),a=n.redirected?l:void 0,i=n.headers.get("content-type")||"",d=!!n.headers.get(r.NEXT_DID_POSTPONE_HEADER),_=!!(null==(y=n.headers.get("vary"))?void 0:y.includes(r.NEXT_URL)),v=i===r.RSC_CONTENT_TYPE_HEADER;if(v||(v=i.startsWith("text/plain")),!v||!n.ok)return e.hash&&(l.hash=e.hash),s(l.toString());let[b,g]=await c(Promise.resolve(n),{callServer:u.callServer});if(f!==b)return s(n.url);return[g,a,d,_]}catch(t){return console.error("Failed to fetch RSC payload for "+e+". Falling back to browser navigation.",t),[e.toString(),void 0,!1,!1]}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},92576:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return function e(t,n,l,a){let i=l.length<=5,[c,s]=l,f=(0,u.createRouterCacheKey)(s),d=n.parallelRoutes.get(c);if(!d)return;let p=t.parallelRoutes.get(c);p&&p!==d||(p=new Map(d),t.parallelRoutes.set(c,p));let h=d.get(f),y=p.get(f);if(i){if(!y||!y.lazyData||y===h){let e=l[3];y={lazyData:null,rsc:e[2],prefetchRsc:null,head:null,prefetchHead:null,loading:e[3],parallelRoutes:h?new Map(h.parallelRoutes):new Map,lazyDataResolved:!1},h&&(0,r.invalidateCacheByRouterState)(y,h,l[2]),(0,o.fillLazyItemsTillLeafWithHead)(y,h,l[2],e,l[4],a),p.set(f,y)}return}y&&h&&(y===h&&(y={lazyData:y.lazyData,rsc:y.rsc,prefetchRsc:y.prefetchRsc,head:y.head,prefetchHead:y.prefetchHead,parallelRoutes:new Map(y.parallelRoutes),lazyDataResolved:!1,loading:y.loading},p.set(f,y)),e(y,h,l.slice(2),a))}}});let r=n(94377),o=n(27420),u=n(78505);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},27420:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return function e(t,n,u,l,a,i){if(0===Object.keys(u[1]).length){t.head=a;return}for(let c in u[1]){let s;let f=u[1][c],d=f[0],p=(0,r.createRouterCacheKey)(d),h=null!==l&&void 0!==l[1][c]?l[1][c]:null;if(n){let r=n.parallelRoutes.get(c);if(r){let n;let u=(null==i?void 0:i.kind)==="auto"&&i.status===o.PrefetchCacheEntryStatus.reusable,l=new Map(r),s=l.get(p);n=null!==h?{lazyData:null,rsc:h[2],prefetchRsc:null,head:null,prefetchHead:null,loading:h[3],parallelRoutes:new Map(null==s?void 0:s.parallelRoutes),lazyDataResolved:!1}:u&&s?{lazyData:s.lazyData,rsc:s.rsc,prefetchRsc:s.prefetchRsc,head:s.head,prefetchHead:s.prefetchHead,parallelRoutes:new Map(s.parallelRoutes),lazyDataResolved:s.lazyDataResolved,loading:s.loading}:{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map(null==s?void 0:s.parallelRoutes),lazyDataResolved:!1,loading:null},l.set(p,n),e(n,s,f,h||null,a,i),t.parallelRoutes.set(c,l);continue}}if(null!==h){let e=h[2],t=h[3];s={lazyData:null,rsc:e,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:t}}else s={lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,lazyDataResolved:!1,loading:null};let y=t.parallelRoutes.get(c);y?y.set(p,s):t.parallelRoutes.set(c,new Map([[p,s]])),e(s,void 0,f,h,a,i)}}}});let r=n(78505),o=n(24673);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},44510:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleMutable",{enumerable:!0,get:function(){return u}});let r=n(5410);function o(e){return void 0!==e}function u(e,t){var n,u,l;let a=null==(u=t.shouldScroll)||u,i=e.nextUrl;if(o(t.patchedTree)){let n=(0,r.computeChangedPath)(e.tree,t.patchedTree);n?i=n:i||(i=e.canonicalUrl)}return{buildId:e.buildId,canonicalUrl:o(t.canonicalUrl)?t.canonicalUrl===e.canonicalUrl?e.canonicalUrl:t.canonicalUrl:e.canonicalUrl,pushRef:{pendingPush:o(t.pendingPush)?t.pendingPush:e.pushRef.pendingPush,mpaNavigation:o(t.mpaNavigation)?t.mpaNavigation:e.pushRef.mpaNavigation,preserveCustomHistoryState:o(t.preserveCustomHistoryState)?t.preserveCustomHistoryState:e.pushRef.preserveCustomHistoryState},focusAndScrollRef:{apply:!!a&&(!!o(null==t?void 0:t.scrollableSegments)||e.focusAndScrollRef.apply),onlyHashChange:!!t.hashFragment&&e.canonicalUrl.split("#",1)[0]===(null==(n=t.canonicalUrl)?void 0:n.split("#",1)[0]),hashFragment:a?t.hashFragment&&""!==t.hashFragment?decodeURIComponent(t.hashFragment.slice(1)):e.focusAndScrollRef.hashFragment:null,segmentPaths:a?null!=(l=null==t?void 0:t.scrollableSegments)?l:e.focusAndScrollRef.segmentPaths:[]},cache:t.cache?t.cache:e.cache,prefetchCache:t.prefetchCache?t.prefetchCache:e.prefetchCache,tree:o(t.patchedTree)?t.patchedTree:e.tree,nextUrl:i}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},77831:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSegmentMismatch",{enumerable:!0,get:function(){return o}});let r=n(95967);function o(e,t,n){return(0,r.handleExternalUrl)(e,{},e.canonicalUrl,!0)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},77058:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheBelowFlightSegmentPath",{enumerable:!0,get:function(){return function e(t,n,o){let u=o.length<=2,[l,a]=o,i=(0,r.createRouterCacheKey)(a),c=n.parallelRoutes.get(l);if(!c)return;let s=t.parallelRoutes.get(l);if(s&&s!==c||(s=new Map(c),t.parallelRoutes.set(l,s)),u){s.delete(i);return}let f=c.get(i),d=s.get(i);d&&f&&(d===f&&(d={lazyData:d.lazyData,rsc:d.rsc,prefetchRsc:d.prefetchRsc,head:d.head,prefetchHead:d.prefetchHead,parallelRoutes:new Map(d.parallelRoutes),lazyDataResolved:d.lazyDataResolved},s.set(i,d)),e(d,f,o.slice(2)))}}});let r=n(78505);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},94377:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheByRouterState",{enumerable:!0,get:function(){return o}});let r=n(78505);function o(e,t,n){for(let o in n[1]){let u=n[1][o][0],l=(0,r.createRouterCacheKey)(u),a=t.parallelRoutes.get(o);if(a){let t=new Map(a);t.delete(l),e.parallelRoutes.set(o,t)}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},63237:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNavigatingToNewRootLayout",{enumerable:!0,get:function(){return function e(t,n){let r=t[0],o=n[0];if(Array.isArray(r)&&Array.isArray(o)){if(r[0]!==o[0]||r[2]!==o[2])return!0}else if(r!==o)return!0;if(t[4])return!n[4];if(n[4])return!0;let u=Object.values(t[1])[0],l=Object.values(n[1])[0];return!u||!l||e(u,l)}}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},56118:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{abortTask:function(){return c},listenForDynamicRequest:function(){return a},updateCacheNodeOnNavigation:function(){return function e(t,n,a,c,s){let f=n[1],d=a[1],p=c[1],h=t.parallelRoutes,y=new Map(h),_={},v=null;for(let t in d){let n;let a=d[t],c=f[t],b=h.get(t),g=p[t],m=a[0],R=(0,u.createRouterCacheKey)(m),P=void 0!==c?c[0]:void 0,j=void 0!==b?b.get(R):void 0;if(null!==(n=m===r.PAGE_SEGMENT_KEY?l(a,void 0!==g?g:null,s):m===r.DEFAULT_SEGMENT_KEY?void 0!==c?{route:c,node:null,children:null}:l(a,void 0!==g?g:null,s):void 0!==P&&(0,o.matchSegment)(m,P)&&void 0!==j&&void 0!==c?null!=g?e(j,c,a,g,s):function(e){let t=i(e,null,null);return{route:e,node:t,children:null}}(a):l(a,void 0!==g?g:null,s))){null===v&&(v=new Map),v.set(t,n);let e=n.node;if(null!==e){let n=new Map(b);n.set(R,e),y.set(t,n)}_[t]=n.route}else _[t]=a}if(null===v)return null;let b={lazyData:null,rsc:t.rsc,prefetchRsc:t.prefetchRsc,head:t.head,prefetchHead:t.prefetchHead,loading:t.loading,parallelRoutes:y,lazyDataResolved:!1};return{route:function(e,t){let n=[e[0],t];return 2 in e&&(n[2]=e[2]),3 in e&&(n[3]=e[3]),4 in e&&(n[4]=e[4]),n}(a,_),node:b,children:v}}},updateCacheNodeOnPopstateRestoration:function(){return function e(t,n){let r=n[1],o=t.parallelRoutes,l=new Map(o);for(let t in r){let n=r[t],a=n[0],i=(0,u.createRouterCacheKey)(a),c=o.get(t);if(void 0!==c){let r=c.get(i);if(void 0!==r){let o=e(r,n),u=new Map(c);u.set(i,o),l.set(t,u)}}}let a=t.rsc,i=d(a)&&"pending"===a.status;return{lazyData:null,rsc:a,head:t.head,prefetchHead:i?t.prefetchHead:null,prefetchRsc:i?t.prefetchRsc:null,loading:i?t.loading:null,parallelRoutes:l,lazyDataResolved:!1}}}});let r=n(84541),o=n(76015),u=n(78505);function l(e,t,n){let r=i(e,t,n);return{route:e,node:r,children:null}}function a(e,t){t.then(t=>{for(let n of t[0]){let t=n.slice(0,-3),r=n[n.length-3],l=n[n.length-2],a=n[n.length-1];"string"!=typeof t&&function(e,t,n,r,l){let a=e;for(let e=0;e{c(e,t)})}function i(e,t,n){let r=e[1],o=null!==t?t[1]:null,l=new Map;for(let e in r){let t=r[e],a=null!==o?o[e]:null,c=t[0],s=(0,u.createRouterCacheKey)(c),f=i(t,void 0===a?null:a,n),d=new Map;d.set(s,f),l.set(e,d)}let a=0===l.size,c=null!==t?t[2]:null,s=null!==t?t[3]:null;return{lazyData:null,parallelRoutes:l,prefetchRsc:void 0!==c?c:null,prefetchHead:a?n:null,loading:void 0!==s?s:null,rsc:p(),head:a?p():null,lazyDataResolved:!1}}function c(e,t){let n=e.node;if(null===n)return;let r=e.children;if(null===r)s(e.route,n,t);else for(let e of r.values())c(e,t);e.node=null}function s(e,t,n){let r=e[1],o=t.parallelRoutes;for(let e in r){let t=r[e],l=o.get(e);if(void 0===l)continue;let a=t[0],i=(0,u.createRouterCacheKey)(a),c=l.get(i);void 0!==c&&s(t,c,n)}let l=t.rsc;d(l)&&(null===n?l.resolve(null):l.reject(n));let a=t.head;d(a)&&a.resolve(null)}let f=Symbol();function d(e){return e&&e.tag===f}function p(){let e,t;let n=new Promise((n,r)=>{e=n,t=r});return n.status="pending",n.resolve=t=>{"pending"===n.status&&(n.status="fulfilled",n.value=t,e(t))},n.reject=e=>{"pending"===n.status&&(n.status="rejected",n.reason=e,t(e))},n.tag=f,n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},60305:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{createPrefetchCacheEntryForInitialLoad:function(){return c},getOrCreatePrefetchCacheEntry:function(){return i},prunePrefetchCache:function(){return f}});let r=n(33456),o=n(44848),u=n(24673),l=n(24819);function a(e,t){let n=(0,r.createHrefFromUrl)(e,!1);return t?t+"%"+n:n}function i(e){let t,{url:n,nextUrl:r,tree:o,buildId:l,prefetchCache:i,kind:c}=e,f=a(n,r),d=i.get(f);if(d)t=d;else{let e=a(n),r=i.get(e);r&&(t=r)}return t?(t.status=h(t),t.kind!==u.PrefetchKind.FULL&&c===u.PrefetchKind.FULL)?s({tree:o,url:n,buildId:l,nextUrl:r,prefetchCache:i,kind:null!=c?c:u.PrefetchKind.TEMPORARY}):(c&&t.kind===u.PrefetchKind.TEMPORARY&&(t.kind=c),t):s({tree:o,url:n,buildId:l,nextUrl:r,prefetchCache:i,kind:c||u.PrefetchKind.TEMPORARY})}function c(e){let{nextUrl:t,tree:n,prefetchCache:r,url:o,kind:l,data:i}=e,[,,,c]=i,s=c?a(o,t):a(o),f={treeAtTimeOfPrefetch:n,data:Promise.resolve(i),kind:l,prefetchTime:Date.now(),lastUsedTime:Date.now(),key:s,status:u.PrefetchCacheEntryStatus.fresh};return r.set(s,f),f}function s(e){let{url:t,kind:n,tree:r,nextUrl:i,buildId:c,prefetchCache:s}=e,f=a(t),d=l.prefetchQueue.enqueue(()=>(0,o.fetchServerResponse)(t,r,i,c,n).then(e=>{let[,,,n]=e;return n&&function(e){let{url:t,nextUrl:n,prefetchCache:r}=e,o=a(t),u=r.get(o);if(!u)return;let l=a(t,n);r.set(l,u),r.delete(o)}({url:t,nextUrl:i,prefetchCache:s}),e})),p={treeAtTimeOfPrefetch:r,data:d,kind:n,prefetchTime:Date.now(),lastUsedTime:null,key:f,status:u.PrefetchCacheEntryStatus.fresh};return s.set(f,p),p}function f(e){for(let[t,n]of e)h(n)===u.PrefetchCacheEntryStatus.expired&&e.delete(t)}let d=1e3*Number("30"),p=1e3*Number("300");function h(e){let{kind:t,prefetchTime:n,lastUsedTime:r}=e;return Date.now()<(null!=r?r:n)+d?r?u.PrefetchCacheEntryStatus.reusable:u.PrefetchCacheEntryStatus.fresh:"auto"===t&&Date.now(){let[n,f]=t,h=!1;if(E.lastUsedTime||(E.lastUsedTime=Date.now(),h=!0),"string"==typeof n)return _(e,R,n,O);if(document.getElementById("__next-page-redirect"))return _(e,R,j,O);let b=e.tree,g=e.cache,w=[];for(let t of n){let n=t.slice(0,-4),r=t.slice(-3)[0],c=["",...n],f=(0,u.applyRouterStatePatchToTree)(c,b,r,j);if(null===f&&(f=(0,u.applyRouterStatePatchToTree)(c,S,r,j)),null!==f){if((0,a.isNavigatingToNewRootLayout)(b,f))return _(e,R,j,O);let u=(0,d.createEmptyCacheNode)(),m=!1;for(let e of(E.status!==i.PrefetchCacheEntryStatus.stale||h?m=(0,s.applyFlightData)(g,u,t,E):(m=function(e,t,n,r){let o=!1;for(let u of(e.rsc=t.rsc,e.prefetchRsc=t.prefetchRsc,e.loading=t.loading,e.parallelRoutes=new Map(t.parallelRoutes),v(r).map(e=>[...n,...e])))(0,y.clearCacheNodeDataForSegmentPath)(e,t,u),o=!0;return o}(u,g,n,r),E.lastUsedTime=Date.now()),(0,l.shouldHardNavigate)(c,b)?(u.rsc=g.rsc,u.prefetchRsc=g.prefetchRsc,(0,o.invalidateCacheBelowFlightSegmentPath)(u,g,n),R.cache=u):m&&(R.cache=u,g=u),b=f,v(r))){let t=[...n,...e];t[t.length-1]!==p.DEFAULT_SEGMENT_KEY&&w.push(t)}}}return R.patchedTree=b,R.canonicalUrl=f?(0,r.createHrefFromUrl)(f):j,R.pendingPush=O,R.scrollableSegments=w,R.hashFragment=P,R.shouldScroll=m,(0,c.handleMutable)(e,R)},()=>e)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},24819:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{prefetchQueue:function(){return l},prefetchReducer:function(){return a}});let r=n(6866),o=n(29744),u=n(60305),l=new o.PromiseQueue(5);function a(e,t){(0,u.prunePrefetchCache)(e.prefetchCache);let{url:n}=t;return n.searchParams.delete(r.NEXT_RSC_UNION_QUERY),(0,u.getOrCreatePrefetchCacheEntry)({url:n,nextUrl:e.nextUrl,prefetchCache:e.prefetchCache,kind:t.kind,tree:e.tree,buildId:e.buildId}),e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},99601:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"refreshReducer",{enumerable:!0,get:function(){return h}});let r=n(44848),o=n(33456),u=n(81935),l=n(63237),a=n(95967),i=n(44510),c=n(27420),s=n(12846),f=n(77831),d=n(28077),p=n(50232);function h(e,t){let{origin:n}=t,h={},y=e.canonicalUrl,_=e.tree;h.preserveCustomHistoryState=!1;let v=(0,s.createEmptyCacheNode)(),b=(0,d.hasInterceptionRouteInCurrentTree)(e.tree);return v.lazyData=(0,r.fetchServerResponse)(new URL(y,n),[_[0],_[1],_[2],"refetch"],b?e.nextUrl:null,e.buildId),v.lazyData.then(async n=>{let[r,s]=n;if("string"==typeof r)return(0,a.handleExternalUrl)(e,h,r,e.pushRef.pendingPush);for(let n of(v.lazyData=null,r)){if(3!==n.length)return console.log("REFRESH FAILED"),e;let[r]=n,i=(0,u.applyRouterStatePatchToTree)([""],_,r,e.canonicalUrl);if(null===i)return(0,f.handleSegmentMismatch)(e,t,r);if((0,l.isNavigatingToNewRootLayout)(_,i))return(0,a.handleExternalUrl)(e,h,y,e.pushRef.pendingPush);let d=s?(0,o.createHrefFromUrl)(s):void 0;s&&(h.canonicalUrl=d);let[g,m]=n.slice(-2);if(null!==g){let e=g[2];v.rsc=e,v.prefetchRsc=null,(0,c.fillLazyItemsTillLeafWithHead)(v,void 0,r,g,m),h.prefetchCache=new Map}await (0,p.refreshInactiveParallelSegments)({state:e,updatedTree:i,updatedCache:v,includeNextUrl:b,canonicalUrl:h.canonicalUrl||e.canonicalUrl}),h.cache=v,h.patchedTree=i,h.canonicalUrl=y,_=i}return(0,i.handleMutable)(e,h)},()=>e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},77784:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"restoreReducer",{enumerable:!0,get:function(){return u}});let r=n(33456),o=n(5410);function u(e,t){var n;let{url:u,tree:l}=t,a=(0,r.createHrefFromUrl)(u),i=l||e.tree,c=e.cache;return{buildId:e.buildId,canonicalUrl:a,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:e.focusAndScrollRef,cache:c,prefetchCache:e.prefetchCache,tree:i,nextUrl:null!=(n=(0,o.extractPathFromFlightRouterState)(i))?n:u.pathname}}n(56118),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},13722:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverActionReducer",{enumerable:!0,get:function(){return m}});let r=n(83079),o=n(6866),u=n(1634),l=n(33456),a=n(95967),i=n(81935),c=n(63237),s=n(44510),f=n(27420),d=n(12846),p=n(28077),h=n(77831),y=n(50232),_=n(91311),{createFromFetch:v,encodeReply:b}=n(6671);async function g(e,t,n){let l,{actionId:a,actionArgs:i}=n,c=await b(i),s=await fetch("",{method:"POST",headers:{Accept:o.RSC_CONTENT_TYPE_HEADER,[o.ACTION]:a,[o.NEXT_ROUTER_STATE_TREE]:(0,_.prepareFlightRouterStateForRequest)(e.tree),...t?{[o.NEXT_URL]:t}:{}},body:c}),f=s.headers.get("x-action-redirect");try{let e=JSON.parse(s.headers.get("x-action-revalidated")||"[[],0,0]");l={paths:e[0]||[],tag:!!e[1],cookie:e[2]}}catch(e){l={paths:[],tag:!1,cookie:!1}}let d=f?new URL((0,u.addBasePath)(f),new URL(e.canonicalUrl,window.location.href)):void 0;if(s.headers.get("content-type")===o.RSC_CONTENT_TYPE_HEADER){let e=await v(Promise.resolve(s),{callServer:r.callServer});if(f){let[,t]=null!=e?e:[];return{actionFlightData:t,redirectLocation:d,revalidatedParts:l}}let[t,[,n]]=null!=e?e:[];return{actionResult:t,actionFlightData:n,redirectLocation:d,revalidatedParts:l}}return{redirectLocation:d,revalidatedParts:l}}function m(e,t){let{resolve:n,reject:r}=t,o={},u=e.canonicalUrl,_=e.tree;o.preserveCustomHistoryState=!1;let v=e.nextUrl&&(0,p.hasInterceptionRouteInCurrentTree)(e.tree)?e.nextUrl:null;return o.inFlightServerAction=g(e,v,t),o.inFlightServerAction.then(async r=>{let{actionResult:p,actionFlightData:b,redirectLocation:g}=r;if(g&&(e.pushRef.pendingPush=!0,o.pendingPush=!0),!b)return(n(p),g)?(0,a.handleExternalUrl)(e,o,g.href,e.pushRef.pendingPush):e;if("string"==typeof b)return(0,a.handleExternalUrl)(e,o,b,e.pushRef.pendingPush);if(o.inFlightServerAction=null,g){let e=(0,l.createHrefFromUrl)(g,!1);o.canonicalUrl=e}for(let n of b){if(3!==n.length)return console.log("SERVER ACTION APPLY FAILED"),e;let[r]=n,s=(0,i.applyRouterStatePatchToTree)([""],_,r,g?(0,l.createHrefFromUrl)(g):e.canonicalUrl);if(null===s)return(0,h.handleSegmentMismatch)(e,t,r);if((0,c.isNavigatingToNewRootLayout)(_,s))return(0,a.handleExternalUrl)(e,o,u,e.pushRef.pendingPush);let[p,b]=n.slice(-2),m=null!==p?p[2]:null;if(null!==m){let t=(0,d.createEmptyCacheNode)();t.rsc=m,t.prefetchRsc=null,(0,f.fillLazyItemsTillLeafWithHead)(t,void 0,r,p,b),await (0,y.refreshInactiveParallelSegments)({state:e,updatedTree:s,updatedCache:t,includeNextUrl:!!v,canonicalUrl:o.canonicalUrl||e.canonicalUrl}),o.cache=t,o.prefetchCache=new Map}o.patchedTree=s,_=s}return n(p),(0,s.handleMutable)(e,o)},t=>(r(t),e))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},68448:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverPatchReducer",{enumerable:!0,get:function(){return f}});let r=n(33456),o=n(81935),u=n(63237),l=n(95967),a=n(22356),i=n(44510),c=n(12846),s=n(77831);function f(e,t){let{serverResponse:n}=t,[f,d]=n,p={};if(p.preserveCustomHistoryState=!1,"string"==typeof f)return(0,l.handleExternalUrl)(e,p,f,e.pushRef.pendingPush);let h=e.tree,y=e.cache;for(let n of f){let i=n.slice(0,-4),[f]=n.slice(-3,-2),_=(0,o.applyRouterStatePatchToTree)(["",...i],h,f,e.canonicalUrl);if(null===_)return(0,s.handleSegmentMismatch)(e,t,f);if((0,u.isNavigatingToNewRootLayout)(h,_))return(0,l.handleExternalUrl)(e,p,e.canonicalUrl,e.pushRef.pendingPush);let v=d?(0,r.createHrefFromUrl)(d):void 0;v&&(p.canonicalUrl=v);let b=(0,c.createEmptyCacheNode)();(0,a.applyFlightData)(y,b,n),p.patchedTree=_,p.cache=b,y=b,h=_}return(0,i.handleMutable)(e,p)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},50232:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{addRefreshMarkerToActiveParallelSegments:function(){return function e(t,n){let[r,o,,l]=t;for(let a in r.includes(u.PAGE_SEGMENT_KEY)&&"refresh"!==l&&(t[2]=n,t[3]="refresh"),o)e(o[a],n)}},refreshInactiveParallelSegments:function(){return l}});let r=n(22356),o=n(44848),u=n(84541);async function l(e){let t=new Set;await a({...e,rootTree:e.updatedTree,fetchedSegments:t})}async function a(e){let{state:t,updatedTree:n,updatedCache:u,includeNextUrl:l,fetchedSegments:i,rootTree:c=n,canonicalUrl:s}=e,[,f,d,p]=n,h=[];if(d&&d!==s&&"refresh"===p&&!i.has(d)){i.add(d);let e=(0,o.fetchServerResponse)(new URL(d,location.origin),[c[0],c[1],c[2],"refetch"],l?t.nextUrl:null,t.buildId).then(e=>{let t=e[0];if("string"!=typeof t)for(let e of t)(0,r.applyFlightData)(u,u,e)});h.push(e)}for(let e in f){let n=a({state:t,updatedTree:f[e],updatedCache:u,includeNextUrl:l,fetchedSegments:i,rootTree:c,canonicalUrl:s});h.push(n)}await Promise.all(h)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},24673:function(e,t){"use strict";var n,r,o,u;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ACTION_FAST_REFRESH:function(){return f},ACTION_NAVIGATE:function(){return a},ACTION_PREFETCH:function(){return s},ACTION_REFRESH:function(){return l},ACTION_RESTORE:function(){return i},ACTION_SERVER_ACTION:function(){return d},ACTION_SERVER_PATCH:function(){return c},PrefetchCacheEntryStatus:function(){return r},PrefetchKind:function(){return n},isThenable:function(){return p}});let l="refresh",a="navigate",i="restore",c="server-patch",s="prefetch",f="fast-refresh",d="server-action";function p(e){return e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(o=n||(n={})).AUTO="auto",o.FULL="full",o.TEMPORARY="temporary",(u=r||(r={})).fresh="fresh",u.reusable="reusable",u.expired="expired",u.stale="stale",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},91450:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return f}});let r=n(24673),o=n(95967),u=n(68448),l=n(77784),a=n(99601),i=n(24819),c=n(44529),s=n(13722),f="undefined"==typeof window?function(e,t){return e}:function(e,t){switch(t.type){case r.ACTION_NAVIGATE:return(0,o.navigateReducer)(e,t);case r.ACTION_SERVER_PATCH:return(0,u.serverPatchReducer)(e,t);case r.ACTION_RESTORE:return(0,l.restoreReducer)(e,t);case r.ACTION_REFRESH:return(0,a.refreshReducer)(e,t);case r.ACTION_FAST_REFRESH:return(0,c.fastRefreshReducer)(e,t);case r.ACTION_PREFETCH:return(0,i.prefetchReducer)(e,t);case r.ACTION_SERVER_ACTION:return(0,s.serverActionReducer)(e,t);default:throw Error("Unknown action")}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},53728:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldHardNavigate",{enumerable:!0,get:function(){return function e(t,n){let[o,u]=n,[l,a]=t;return(0,r.matchSegment)(l,o)?!(t.length<=2)&&e(t.slice(2),u[a]):!!Array.isArray(l)}}});let r=n(76015);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},54535:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{createDynamicallyTrackedSearchParams:function(){return a},createUntrackedSearchParams:function(){return l}});let r=n(51845),o=n(86999),u=n(30650);function l(e){let t=r.staticGenerationAsyncStorage.getStore();return t&&t.forceStatic?{}:e}function a(e){let t=r.staticGenerationAsyncStorage.getStore();return t?t.forceStatic?{}:t.isStaticGeneration||t.dynamicShouldError?new Proxy({},{get:(e,n,r)=>("string"==typeof n&&(0,o.trackDynamicDataAccessed)(t,"searchParams."+n),u.ReflectAdapter.get(e,n,r)),has:(e,n)=>("string"==typeof n&&(0,o.trackDynamicDataAccessed)(t,"searchParams."+n),Reflect.has(e,n)),ownKeys:e=>((0,o.trackDynamicDataAccessed)(t,"searchParams"),Reflect.ownKeys(e))}):e:e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},51845:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationAsyncStorage",{enumerable:!0,get:function(){return r.staticGenerationAsyncStorage}});let r=n(20030);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},36864:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{StaticGenBailoutError:function(){return r},isStaticGenBailoutError:function(){return o}});let n="NEXT_STATIC_GEN_BAILOUT";class r extends Error{constructor(...e){super(...e),this.code=n}}function o(e){return"object"==typeof e&&null!==e&&"code"in e&&e.code===n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},38137:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"unresolvedThenable",{enumerable:!0,get:function(){return n}});let n={then:()=>{}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},47744:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{useReducerWithReduxDevtools:function(){return i},useUnwrapState:function(){return a}});let r=n(53099)._(n(2265)),o=n(24673),u=n(2103);function l(e){if(e instanceof Map){let t={};for(let[n,r]of e.entries()){if("function"==typeof r){t[n]="fn()";continue}if("object"==typeof r&&null!==r){if(r.$$typeof){t[n]=r.$$typeof.toString();continue}if(r._bundlerConfig){t[n]="FlightData";continue}}t[n]=l(r)}return t}if("object"==typeof e&&null!==e){let t={};for(let n in e){let r=e[n];if("function"==typeof r){t[n]="fn()";continue}if("object"==typeof r&&null!==r){if(r.$$typeof){t[n]=r.$$typeof.toString();continue}if(r.hasOwnProperty("_bundlerConfig")){t[n]="FlightData";continue}}t[n]=l(r)}return t}return Array.isArray(e)?e.map(l):e}function a(e){return(0,o.isThenable)(e)?(0,r.use)(e):e}let i="undefined"!=typeof window?function(e){let[t,n]=r.default.useState(e),o=(0,r.useContext)(u.ActionQueueContext);if(!o)throw Error("Invariant: Missing ActionQueueContext");let a=(0,r.useRef)(),i=(0,r.useRef)();return(0,r.useEffect)(()=>{if(!a.current&&!1!==i.current){if(void 0===i.current&&void 0===window.__REDUX_DEVTOOLS_EXTENSION__){i.current=!1;return}return a.current=window.__REDUX_DEVTOOLS_EXTENSION__.connect({instanceId:8e3,name:"next-router"}),a.current&&(a.current.init(l(e)),o&&(o.devToolsInstance=a.current)),()=>{a.current=void 0}}},[e,o]),[t,(0,r.useCallback)(t=>{o.state||(o.state=e),o.dispatch(t,n)},[o,e]),(0,r.useCallback)(e=>{a.current&&a.current.send({type:"RENDER_SYNC"},l(e))},[])]}:function(e){return[e,()=>{},()=>{}]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},91311:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prepareFlightRouterStateForRequest",{enumerable:!0,get:function(){return o}});let r=n(84541);function o(e,t){return t?encodeURIComponent(JSON.stringify(e)):encodeURIComponent(JSON.stringify(function e(t){let[n,o,,u,l]=t,a="string"==typeof n&&n.startsWith(r.PAGE_SEGMENT_KEY+"?")?r.PAGE_SEGMENT_KEY:n,i={};for(let[t,n]of Object.entries(o))i[t]=e(n);let c=[a,i,null,u&&"refresh"!==u?u:null];return void 0!==l&&(c[4]=l),c}(e)))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},11283:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return o}});let r=n(10580);function o(e){return(0,r.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},33068:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return u}});let r=n(26674),o=n(63381),u=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:n,hash:u}=(0,o.parsePath)(e);return""+(0,r.removeTrailingSlash)(t)+n+u};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},61404:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return o}});let r=n(18993);function o(e){let t="function"==typeof reportError?reportError:e=>{window.console.error(e)};(0,r.isBailoutToCSRError)(e)||t(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},35076:function(e,t,n){"use strict";function r(e){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return r}}),n(11283),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},12010:function(e,t){"use strict";function n(e,t){var n=e.length;for(e.push(t);0>>1,o=e[r];if(0>>1;ru(i,n))cu(s,i)?(e[r]=s,e[c]=n,r=c):(e[r]=i,e[a]=n,r=a);else if(cu(s,n))e[r]=s,e[c]=n,r=c;else break}}return t}function u(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}if(t.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var l,a=performance;t.unstable_now=function(){return a.now()}}else{var i=Date,c=i.now();t.unstable_now=function(){return i.now()-c}}var s=[],f=[],d=1,p=null,h=3,y=!1,_=!1,v=!1,b="function"==typeof setTimeout?setTimeout:null,g="function"==typeof clearTimeout?clearTimeout:null,m="undefined"!=typeof setImmediate?setImmediate:null;function R(e){for(var t=r(f);null!==t;){if(null===t.callback)o(f);else if(t.startTime<=e)o(f),t.sortIndex=t.expirationTime,n(s,t);else break;t=r(f)}}function P(e){if(v=!1,R(e),!_){if(null!==r(s))_=!0,C();else{var t=r(f);null!==t&&A(P,t.startTime-e)}}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var j=!1,O=-1,E=5,S=-1;function w(){return!(t.unstable_now()-Se&&w());){var a=p.callback;if("function"==typeof a){p.callback=null,h=p.priorityLevel;var i=a(p.expirationTime<=e);if(e=t.unstable_now(),"function"==typeof i){p.callback=i,R(e),n=!0;break t}p===r(s)&&o(s),R(e)}else o(s);p=r(s)}if(null!==p)n=!0;else{var c=r(f);null!==c&&A(P,c.startTime-e),n=!1}}break e}finally{p=null,h=u,y=!1}n=void 0}}finally{n?l():j=!1}}}if("function"==typeof m)l=function(){m(M)};else if("undefined"!=typeof MessageChannel){var T=new MessageChannel,x=T.port2;T.port1.onmessage=M,l=function(){x.postMessage(null)}}else l=function(){b(M,0)};function C(){j||(j=!0,l())}function A(e,n){O=b(function(){e(t.unstable_now())},n)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){_||y||(_=!0,C())},t.unstable_forceFrameRate=function(e){0>e||125l?(e.sortIndex=u,n(f,e),null===r(s)&&e===r(f)&&(v?(g(O),O=-1):v=!0,A(P,u-l))):(e.sortIndex=a,n(s,e),_||y||(_=!0,C())),e},t.unstable_shouldYield=w,t.unstable_wrapCallback=function(e){var t=h;return function(){var n=h;h=t;try{return e.apply(this,arguments)}finally{h=n}}}},71767:function(e,t,n){"use strict";e.exports=n(12010)},60934:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getPathname:function(){return r},isFullStringUrl:function(){return o},parseUrl:function(){return u}});let n="http://n";function r(e){return new URL(e,n).pathname}function o(e){return/https?:\/\//.test(e)}function u(e){let t;try{t=new URL(e,n)}catch{}return t}},86999:function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{Postpone:function(){return d},createPostponedAbortSignal:function(){return b},createPrerenderState:function(){return c},formatDynamicAPIAccesses:function(){return _},markCurrentScopeAsDynamic:function(){return s},trackDynamicDataAccessed:function(){return f},trackDynamicFetch:function(){return p},usedDynamicAPIs:function(){return y}});let o=(r=n(2265))&&r.__esModule?r:{default:r},u=n(46177),l=n(36864),a=n(60934),i="function"==typeof o.default.unstable_postpone;function c(e){return{isDebugSkeleton:e,dynamicAccesses:[]}}function s(e,t){let n=(0,a.getPathname)(e.urlPathname);if(!e.isUnstableCacheCallback){if(e.dynamicShouldError)throw new l.StaticGenBailoutError(`Route ${n} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${t}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);if(e.prerenderState)h(e.prerenderState,t,n);else if(e.revalidate=0,e.isStaticGeneration){let r=new u.DynamicServerError(`Route ${n} couldn't be rendered statically because it used ${t}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`);throw e.dynamicUsageDescription=t,e.dynamicUsageStack=r.stack,r}}}function f(e,t){let n=(0,a.getPathname)(e.urlPathname);if(e.isUnstableCacheCallback)throw Error(`Route ${n} used "${t}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${t}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`);if(e.dynamicShouldError)throw new l.StaticGenBailoutError(`Route ${n} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${t}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);if(e.prerenderState)h(e.prerenderState,t,n);else if(e.revalidate=0,e.isStaticGeneration){let r=new u.DynamicServerError(`Route ${n} couldn't be rendered statically because it used \`${t}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`);throw e.dynamicUsageDescription=t,e.dynamicUsageStack=r.stack,r}}function d({reason:e,prerenderState:t,pathname:n}){h(t,e,n)}function p(e,t){e.prerenderState&&h(e.prerenderState,t,e.urlPathname)}function h(e,t,n){v();let r=`Route ${n} needs to bail out of prerendering at this point because it used ${t}. React throws this special object to indicate where. It should not be caught by your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`;e.dynamicAccesses.push({stack:e.isDebugSkeleton?Error().stack:void 0,expression:t}),o.default.unstable_postpone(r)}function y(e){return e.dynamicAccesses.length>0}function _(e){return e.dynamicAccesses.filter(e=>"string"==typeof e.stack&&e.stack.length>0).map(({expression:e,stack:t})=>(t=t.split("\n").slice(4).filter(e=>!(e.includes("node_modules/next/")||e.includes(" ()")||e.includes(" (node:"))).join("\n"),`Dynamic API Usage Debug - ${e}: +${t}`))}function v(){if(!i)throw Error("Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js")}function b(e){v();let t=new AbortController;try{o.default.unstable_postpone(e)}catch(e){t.abort(e)}return t.signal}},87417:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentParam",{enumerable:!0,get:function(){return o}});let r=n(91182);function o(e){let t=r.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t));return(t&&(e=e.slice(t.length)),e.startsWith("[[...")&&e.endsWith("]]"))?{type:"optional-catchall",param:e.slice(5,-2)}:e.startsWith("[...")&&e.endsWith("]")?{type:t?"catchall-intercepted":"catchall",param:e.slice(4,-1)}:e.startsWith("[")&&e.endsWith("]")?{type:t?"dynamic-intercepted":"dynamic",param:e.slice(1,-1)}:null}},70647:function(e,t){"use strict";var n,r;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HMR_ACTIONS_SENT_TO_BROWSER",{enumerable:!0,get:function(){return n}}),(r=n||(n={})).ADDED_PAGE="addedPage",r.REMOVED_PAGE="removedPage",r.RELOAD_PAGE="reloadPage",r.SERVER_COMPONENT_CHANGES="serverComponentChanges",r.MIDDLEWARE_CHANGES="middlewareChanges",r.CLIENT_CHANGES="clientChanges",r.SERVER_ONLY_CHANGES="serverOnlyChanges",r.SYNC="sync",r.BUILT="built",r.BUILDING="building",r.DEV_PAGES_MANIFEST_UPDATE="devPagesManifestUpdate",r.TURBOPACK_MESSAGE="turbopack-message",r.SERVER_ERROR="serverError",r.TURBOPACK_CONNECTED="turbopack-connected"},91182:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return o},extractInterceptionRouteInformation:function(){return l},isInterceptionRouteAppPath:function(){return u}});let r=n(20926),o=["(..)(..)","(.)","(..)","(...)"];function u(e){return void 0!==e.split("/").find(e=>o.find(t=>e.startsWith(t)))}function l(e){let t,n,u;for(let r of e.split("/"))if(n=o.find(e=>r.startsWith(e))){[t,u]=e.split(n,2);break}if(!t||!n||!u)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,r.normalizeAppPath)(t),n){case"(.)":u="/"===t?`/${u}`:t+"/"+u;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);u=t.split("/").slice(0,-1).concat(u).join("/");break;case"(...)":u="/"+u;break;case"(..)(..)":let l=t.split("/");if(l.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);u=l.slice(0,-2).concat(u).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:u}}},30650:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ReflectAdapter",{enumerable:!0,get:function(){return n}});class n{static get(e,t,n){let r=Reflect.get(e,t,n);return"function"==typeof r?r.bind(e):r}static set(e,t,n,r){return Reflect.set(e,t,n,r)}static has(e,t){return Reflect.has(e,t)}static deleteProperty(e,t){return Reflect.deleteProperty(e,t)}}},61956:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{AppRouterContext:function(){return o},GlobalLayoutRouterContext:function(){return l},LayoutRouterContext:function(){return u},MissingSlotContext:function(){return i},TemplateContext:function(){return a}});let r=n(47043)._(n(2265)),o=r.default.createContext(null),u=r.default.createContext(null),l=r.default.createContext(null),a=r.default.createContext(null),i=r.default.createContext(new Set)},37207:function(e,t){"use strict";function n(e){let t=5381;for(let n=0;n>>0}function r(e){return n(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{djb2Hash:function(){return n},hexHash:function(){return r}})},48701:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HeadManagerContext",{enumerable:!0,get:function(){return r}});let r=n(47043)._(n(2265)).default.createContext({})},79060:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{PathParamsContext:function(){return l},PathnameContext:function(){return u},SearchParamsContext:function(){return o}});let r=n(2265),o=(0,r.createContext)(null),u=(0,r.createContext)(null),l=(0,r.createContext)(null)},18993:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{BailoutToCSRError:function(){return r},isBailoutToCSRError:function(){return o}});let n="BAILOUT_TO_CLIENT_SIDE_RENDERING";class r extends Error{constructor(e){super("Bail out to client-side rendering: "+e),this.reason=e,this.digest=n}}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&e.digest===n}},78162:function(e,t){"use strict";function n(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return n}})},2103:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ActionQueueContext:function(){return a},createMutableActionQueue:function(){return s}});let r=n(53099),o=n(24673),u=n(91450),l=r._(n(2265)),a=l.default.createContext(null);function i(e,t){null!==e.pending&&(e.pending=e.pending.next,null!==e.pending?c({actionQueue:e,action:e.pending,setState:t}):e.needsRefresh&&(e.needsRefresh=!1,e.dispatch({type:o.ACTION_REFRESH,origin:window.location.origin},t)))}async function c(e){let{actionQueue:t,action:n,setState:r}=e,u=t.state;if(!u)throw Error("Invariant: Router state not initialized");t.pending=n;let l=n.payload,a=t.action(u,l);function c(e){n.discarded||(t.state=e,t.devToolsInstance&&t.devToolsInstance.send(l,e),i(t,r),n.resolve(e))}(0,o.isThenable)(a)?a.then(c,e=>{i(t,r),n.reject(e)}):c(a)}function s(){let e={state:null,dispatch:(t,n)=>(function(e,t,n){let r={resolve:n,reject:()=>{}};if(t.type!==o.ACTION_RESTORE){let e=new Promise((e,t)=>{r={resolve:e,reject:t}});(0,l.startTransition)(()=>{n(e)})}let u={payload:t,next:null,resolve:r.resolve,reject:r.reject};null===e.pending?(e.last=u,c({actionQueue:e,action:u,setState:n})):t.type===o.ACTION_NAVIGATE||t.type===o.ACTION_RESTORE?(e.pending.discarded=!0,e.last=u,e.pending.payload.type===o.ACTION_SERVER_ACTION&&(e.needsRefresh=!0),c({actionQueue:e,action:u,setState:n})):(null!==e.last&&(e.last.next=u),e.last=u)})(e,t,n),action:async(e,t)=>{if(null===e)throw Error("Invariant: Router state not initialized");return(0,u.reducer)(e,t)},pending:null,last:null};return e}},68498:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return o}});let r=n(63381);function o(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:n,query:o,hash:u}=(0,r.parsePath)(e);return""+t+n+o+u}},20926:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{normalizeAppPath:function(){return u},normalizeRscURL:function(){return l}});let r=n(78162),o=n(84541);function u(e){return(0,r.ensureLeadingSlash)(e.split("/").reduce((e,t,n,r)=>!t||(0,o.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&n===r.length-1?e:e+"/"+t,""))}function l(e){return e.replace(/\.rsc($|\?)/,"$1")}},7092:function(e,t){"use strict";function n(e,t){if(void 0===t&&(t={}),t.onlyHashChange){e();return}let n=document.documentElement,r=n.style.scrollBehavior;n.style.scrollBehavior="auto",t.dontForceLayout||n.getClientRects(),e(),n.style.scrollBehavior=r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return n}})},86146:function(e,t){"use strict";function n(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isBot",{enumerable:!0,get:function(){return n}})},63381:function(e,t){"use strict";function n(e){let t=e.indexOf("#"),n=e.indexOf("?"),r=n>-1&&(t<0||n-1?{pathname:e.substring(0,r?n:t),query:r?e.substring(n,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return n}})},10580:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return o}});let r=n(63381);function o(e,t){if("string"!=typeof e)return!1;let{pathname:n}=(0,r.parsePath)(e);return n===t||n.startsWith(t+"/")}},26674:function(e,t){"use strict";function n(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return n}})},84541:function(e,t){"use strict";function n(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{DEFAULT_SEGMENT_KEY:function(){return o},PAGE_SEGMENT_KEY:function(){return r},isGroupSegment:function(){return n}});let r="__PAGE__",o="__DEFAULT__"},55501:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ServerInsertedHTMLContext:function(){return o},useServerInsertedHTML:function(){return u}});let r=n(53099)._(n(2265)),o=r.default.createContext(null);function u(e){let t=(0,r.useContext)(o);t&&t(e)}},31765:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return n}});let n=e=>{}},47149:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"actionAsyncStorage",{enumerable:!0,get:function(){return r}});let r=(0,n(54832).createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},54832:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createAsyncLocalStorage",{enumerable:!0,get:function(){return u}});let n=Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available");class r{disable(){throw n}getStore(){}run(){throw n}exit(){throw n}enterWith(){throw n}}let o=globalThis.AsyncLocalStorage;function u(){return o?new o:new r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},25575:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"requestAsyncStorage",{enumerable:!0,get:function(){return r}});let r=(0,n(54832).createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},20030:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationAsyncStorage",{enumerable:!0,get:function(){return r}});let r=(0,n(54832).createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},34040:function(e,t,n){"use strict";var r=n(54887);t.createRoot=r.createRoot,t.hydrateRoot=r.hydrateRoot},54887:function(e,t,n){"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=n(84417)},97950:function(e,t,n){"use strict";var r=n(54887),o={stream:!0},u=new Map;function l(e){var t=n(e);return"function"!=typeof t.then||"fulfilled"===t.status?null:(t.then(function(e){t.status="fulfilled",t.value=e},function(e){t.status="rejected",t.reason=e}),t)}function a(){}var i=new Map,c=n.u;n.u=function(e){var t=i.get(e);return void 0!==t?t:c(e)};var s=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher,f=Symbol.for("react.element"),d=Symbol.for("react.lazy"),p=Symbol.iterator,h=Array.isArray,y=Object.getPrototypeOf,_=Object.prototype,v=new WeakMap;function b(e,t,n,r){this.status=e,this.value=t,this.reason=n,this._response=r}function g(e){switch(e.status){case"resolved_model":S(e);break;case"resolved_module":w(e)}switch(e.status){case"fulfilled":return e.value;case"pending":case"blocked":case"cyclic":throw e;default:throw e.reason}}function m(e,t){for(var n=0;nh?(_=h,h=3,p++):(_=0,h=3);continue;case 2:44===(m=d[p++])?h=4:v=v<<4|(96d.length&&(m=-1)}var O=d.byteOffset+p;if(-1{var e,l,t,a,i,r,n;h.setFieldsValue({user_id:s.user_id,user_email:null===(e=s.user_info)||void 0===e?void 0:e.user_email,user_alias:null===(l=s.user_info)||void 0===l?void 0:l.user_alias,user_role:null===(t=s.user_info)||void 0===t?void 0:t.user_role,models:(null===(a=s.user_info)||void 0===a?void 0:a.models)||[],max_budget:null===(i=s.user_info)||void 0===i?void 0:i.max_budget,budget_duration:null===(r=s.user_info)||void 0===r?void 0:r.budget_duration,metadata:(null===(n=s.user_info)||void 0===n?void 0:n.metadata)?JSON.stringify(s.user_info.metadata,null,2):void 0})},[s,h]),(0,t.jsxs)(p.Z,{form:h,onFinish:e=>{if(e.metadata&&"string"==typeof e.metadata)try{e.metadata=JSON.parse(e.metadata)}catch(e){console.error("Error parsing metadata JSON:",e);return}a(e)},layout:"vertical",children:[!x&&(0,t.jsx)(p.Z.Item,{label:"User ID",name:"user_id",children:(0,t.jsx)(b.Z,{disabled:!0})}),!x&&(0,t.jsx)(p.Z.Item,{label:"Email",name:"user_email",children:(0,t.jsx)(b.Z,{})}),(0,t.jsx)(p.Z.Item,{label:"User Alias",name:"user_alias",children:(0,t.jsx)(b.Z,{})}),(0,t.jsx)(p.Z.Item,{label:(0,t.jsxs)("span",{children:["Global Proxy Role"," ",(0,t.jsx)(f.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,t.jsx)(w.Z,{})})]}),name:"user_role",children:(0,t.jsx)(g.default,{children:m&&Object.entries(m).map(e=>{let[s,{ui_label:l,description:a}]=e;return(0,t.jsx)(_.Z,{value:s,title:l,children:(0,t.jsxs)("div",{className:"flex",children:[l," ",(0,t.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:a})]})},s)})})}),(0,t.jsx)(p.Z.Item,{label:(0,t.jsxs)("span",{children:["Personal Models"," ",(0,t.jsx)(f.Z,{title:"Select which models this user can access outside of team-scope. Choose 'All Proxy Models' to grant access to all models available on the proxy.",children:(0,t.jsx)(w.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,t.jsxs)(g.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:!Z.ZL.includes(c||""),children:[(0,t.jsx)(g.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,t.jsx)(g.default.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),u.map(e=>(0,t.jsx)(g.default.Option,{value:e,children:(0,S.W0)(e)},e))]})}),(0,t.jsx)(p.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(y.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,t.jsx)(p.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsx)(k.Z,{})}),(0,t.jsx)(p.Z.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(N.Z,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,t.jsx)(r.z,{variant:"secondary",type:"button",onClick:l,children:"Cancel"}),(0,t.jsx)(r.z,{type:"submit",children:"Save Changes"})]})]})}var U=l(9114);let{Text:I,Title:D}=n.default;var z=e=>{let{open:s,onCancel:l,selectedUsers:a,possibleUIRoles:r,accessToken:n,onSuccess:p,teams:f,userRole:y,userModels:_,allowAllUsers:b=!1}=e,[N,S]=(0,i.useState)(!1),[Z,w]=(0,i.useState)([]),[k,z]=(0,i.useState)(null),[A,B]=(0,i.useState)(!1),[E,T]=(0,i.useState)(!1),O=()=>{w([]),z(null),B(!1),T(!1),l()},L=i.useMemo(()=>({user_id:"bulk_edit",user_info:{user_email:"",user_role:"",teams:[],models:[],max_budget:null,spend:0,metadata:{},created_at:null,updated_at:null},keys:[],teams:f||[]}),[f,s]),F=async e=>{if(console.log("formValues",e),!n){U.Z.fromBackend("Access token not found");return}S(!0);try{let s=a.map(e=>e.user_id),t={};e.user_role&&""!==e.user_role&&(t.user_role=e.user_role),null!==e.max_budget&&void 0!==e.max_budget&&(t.max_budget=e.max_budget),e.models&&e.models.length>0&&(t.models=e.models),e.budget_duration&&""!==e.budget_duration&&(t.budget_duration=e.budget_duration),e.metadata&&Object.keys(e.metadata).length>0&&(t.metadata=e.metadata);let i=Object.keys(t).length>0,r=A&&Z.length>0;if(!i&&!r){U.Z.fromBackend("Please modify at least one field or select teams to add users to");return}let o=[];if(i){if(E){let e=await (0,j.userBulkUpdateUserCall)(n,t,void 0,!0);o.push("Updated all users (".concat(e.total_requested," total)"))}else await (0,j.userBulkUpdateUserCall)(n,t,s),o.push("Updated ".concat(s.length," user(s)"))}if(r){let e=[];for(let s of Z)try{let l=null;l=E?null:a.map(e=>({user_id:e.user_id,role:"user",user_email:e.user_email||null}));let t=await (0,j.teamBulkMemberAddCall)(n,s,l||null,k||void 0,E);console.log("result",t),e.push({teamId:s,success:!0,successfulAdditions:t.successful_additions,failedAdditions:t.failed_additions})}catch(l){console.error("Failed to add users to team ".concat(s,":"),l),e.push({teamId:s,success:!1,error:l})}let s=e.filter(e=>e.success),l=e.filter(e=>!e.success);if(s.length>0){let e=s.reduce((e,s)=>e+s.successfulAdditions,0);o.push("Added users to ".concat(s.length," team(s) (").concat(e," total additions)"))}l.length>0&&d.ZP.warning("Failed to add users to ".concat(l.length," team(s)"))}o.length>0&&U.Z.success(o.join(". ")),w([]),z(null),B(!1),T(!1),p(),l()}catch(e){console.error("Bulk operation failed:",e),U.Z.fromBackend("Failed to perform bulk operations")}finally{S(!1)}};return(0,t.jsxs)(o.Z,{open:s,onCancel:O,footer:null,title:E?"Bulk Edit All Users":"Bulk Edit ".concat(a.length," User(s)"),width:800,children:[b&&(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(c.Z,{checked:E,onChange:e=>T(e.target.checked),children:(0,t.jsx)(I,{strong:!0,children:"Update ALL users in the system"})}),E&&(0,t.jsx)("div",{style:{marginTop:8},children:(0,t.jsx)(I,{type:"warning",style:{fontSize:"12px"},children:"⚠️ This will apply changes to ALL users in the system, not just the selected ones."})})]}),!E&&(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsxs)(D,{level:5,children:["Selected Users (",a.length,"):"]}),(0,t.jsx)(u.Z,{size:"small",bordered:!0,dataSource:a,pagination:!1,scroll:{y:200},rowKey:"user_id",columns:[{title:"User ID",dataIndex:"user_id",key:"user_id",width:"30%",render:e=>(0,t.jsx)(I,{strong:!0,style:{fontSize:"12px"},children:e.length>20?"".concat(e.slice(0,20),"..."):e})},{title:"Email",dataIndex:"user_email",key:"user_email",width:"25%",render:e=>(0,t.jsx)(I,{type:"secondary",style:{fontSize:"12px"},children:e||"No email"})},{title:"Current Role",dataIndex:"user_role",key:"user_role",width:"25%",render:e=>{var s;return(0,t.jsx)(I,{style:{fontSize:"12px"},children:(null==r?void 0:null===(s=r[e])||void 0===s?void 0:s.ui_label)||e})}},{title:"Budget",dataIndex:"max_budget",key:"max_budget",width:"20%",render:e=>(0,t.jsx)(I,{style:{fontSize:"12px"},children:null!==e?"$".concat(e):"Unlimited"})}]})]}),(0,t.jsx)(m.Z,{}),(0,t.jsx)("div",{className:"mb-4",children:(0,t.jsxs)(I,{children:[(0,t.jsx)("strong",{children:"Instructions:"})," Fill in the fields below with the values you want to apply to all selected users. You can bulk edit: role, budget, models, and metadata. You can also add users to teams."]})}),(0,t.jsx)(x.Z,{title:"Team Management",size:"small",className:"mb-4",style:{backgroundColor:"#fafafa"},children:(0,t.jsxs)(h.Z,{direction:"vertical",style:{width:"100%"},children:[(0,t.jsx)(c.Z,{checked:A,onChange:e=>B(e.target.checked),children:"Add selected users to teams"}),A&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(I,{strong:!0,children:"Select Teams:"}),(0,t.jsx)(g.default,{mode:"multiple",placeholder:"Select teams to add users to",value:Z,onChange:w,style:{width:"100%",marginTop:8},options:(null==f?void 0:f.map(e=>({label:e.team_alias||e.team_id,value:e.team_id})))||[]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(I,{strong:!0,children:"Team Budget (Optional):"}),(0,t.jsx)(v.Z,{placeholder:"Max budget per user in team",value:k,onChange:e=>z(e),style:{width:"100%",marginTop:8},min:0,step:.01,precision:2}),(0,t.jsx)(I,{type:"secondary",style:{fontSize:"12px"},children:"Leave empty for unlimited budget within team limits"})]}),(0,t.jsx)(I,{type:"secondary",style:{fontSize:"12px"},children:'Users will be added with "user" role by default. All users will be added to each selected team.'})]})]})}),(0,t.jsx)(C,{userData:L,onCancel:O,onSubmit:F,teams:f,accessToken:n,userID:"bulk_edit",userRole:y,userModels:_,possibleUIRoles:r,isBulkEdit:!0}),N&&(0,t.jsx)("div",{style:{textAlign:"center",marginTop:"10px"},children:(0,t.jsxs)(I,{children:["Updating ",E?"all users":a.length," user(s)..."]})})]})},A=l(7765),B=l(5545),E=e=>{let{visible:s,possibleUIRoles:l,onCancel:a,user:r,onSubmit:n}=e,[d,c]=(0,i.useState)(r),[u]=p.Z.useForm();(0,i.useEffect)(()=>{u.resetFields()},[r]);let m=async()=>{u.resetFields(),a()},x=async e=>{n(e),u.resetFields(),a()};return r?(0,t.jsx)(o.Z,{visible:s,onCancel:m,footer:null,title:"Edit User "+r.user_id,width:1e3,children:(0,t.jsx)(p.Z,{form:u,onFinish:x,initialValues:r,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(p.Z.Item,{className:"mt-8",label:"User Email",tooltip:"Email of the User",name:"user_email",children:(0,t.jsx)(b.Z,{})}),(0,t.jsx)(p.Z.Item,{label:"user_id",name:"user_id",hidden:!0,children:(0,t.jsx)(b.Z,{})}),(0,t.jsx)(p.Z.Item,{label:"User Role",name:"user_role",children:(0,t.jsx)(g.default,{children:l&&Object.entries(l).map(e=>{let[s,{ui_label:l,description:a}]=e;return(0,t.jsx)(_.Z,{value:s,title:l,children:(0,t.jsxs)("div",{className:"flex",children:[l," ",(0,t.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:a})]})},s)})})}),(0,t.jsx)(p.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,t.jsx)(v.Z,{min:0,step:.01})}),(0,t.jsx)(p.Z.Item,{label:"User Budget (USD)",name:"max_budget",tooltip:"(float) - Maximum budget of this user",help:"Maximum budget of this user.",children:(0,t.jsx)(y.Z,{min:0,step:.01})}),(0,t.jsx)(p.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsx)(k.Z,{})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(B.ZP,{htmlType:"submit",children:"Save"})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(B.ZP,{htmlType:"submit",children:"Save"})})]})})}):null},T=l(98187),O=l(59872),L=l(19616),F=l(29827),R=l(11713),P=l(21609),M=l(88913),K=l(63709),V=l(10353),q=l(26349),G=l(96473),J=e=>{var s;let{accessToken:l,possibleUIRoles:a,userID:r,userRole:d}=e,[o,c]=(0,i.useState)(!0),[u,m]=(0,i.useState)(null),[x,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)({}),[y,_]=(0,i.useState)(!1),[b,N]=(0,i.useState)([]),{Paragraph:Z}=n.default,{Option:w}=g.default;(0,i.useEffect)(()=>{(async()=>{if(!l){c(!1);return}try{let e=await (0,j.getInternalUserSettings)(l);if(m(e),f(e.values||{}),l)try{let e=await (0,j.modelAvailableCall)(l,r,d);if(e&&e.data){let s=e.data.map(e=>e.id);N(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching SSO settings:",e),U.Z.fromBackend("Failed to fetch SSO settings")}finally{c(!1)}})()},[l]);let C=async()=>{if(l){_(!0);try{let e=Object.entries(p).reduce((e,s)=>{let[l,t]=s;return e[l]=""===t?null:t,e},{}),s=await (0,j.updateInternalUserSettings)(l,e);m({...u,values:s.settings}),h(!1)}catch(e){console.error("Error updating SSO settings:",e),U.Z.fromBackend("Failed to update settings: "+e)}finally{_(!1)}}},I=(e,s)=>{f(l=>({...l,[e]:s}))},D=e=>e&&Array.isArray(e)?e.map(e=>"string"==typeof e?{team_id:e,user_role:"user"}:"object"==typeof e&&e.team_id?{team_id:e.team_id,max_budget_in_team:e.max_budget_in_team,user_role:e.user_role||"user"}:{team_id:"",user_role:"user"}):[],z=e=>{let s=D(e),l=(e,l,t)=>{let a=[...s];a[e]={...a[e],[l]:t},I("teams",a)},a=e=>{I("teams",s.filter((s,l)=>l!==e))};return(0,t.jsxs)("div",{className:"space-y-3",children:[s.map((e,s)=>(0,t.jsxs)("div",{className:"border rounded-lg p-4 bg-gray-50",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-3",children:[(0,t.jsxs)(M.xv,{className:"font-medium",children:["Team ",s+1]}),(0,t.jsx)(M.zx,{size:"sm",variant:"secondary",icon:q.Z,onClick:()=>a(s),className:"text-red-500 hover:text-red-700",children:"Remove"})]}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(M.xv,{className:"text-sm font-medium mb-1",children:"Team ID"}),(0,t.jsx)(M.oi,{value:e.team_id,onChange:e=>l(s,"team_id",e.target.value),placeholder:"Enter team ID"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(M.xv,{className:"text-sm font-medium mb-1",children:"Max Budget in Team"}),(0,t.jsx)(v.Z,{style:{width:"100%"},value:e.max_budget_in_team,onChange:e=>l(s,"max_budget_in_team",e),placeholder:"Optional",min:0,step:.01,precision:2})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(M.xv,{className:"text-sm font-medium mb-1",children:"User Role"}),(0,t.jsxs)(g.default,{style:{width:"100%"},value:e.user_role,onChange:e=>l(s,"user_role",e),children:[(0,t.jsx)(w,{value:"user",children:"User"}),(0,t.jsx)(w,{value:"admin",children:"Admin"})]})]})]})]},s)),(0,t.jsx)(M.zx,{variant:"secondary",icon:G.Z,onClick:()=>{I("teams",[...s,{team_id:"",user_role:"user"}])},className:"w-full",children:"Add Team"})]})},A=(e,s,l)=>{var i;let r=s.type;if("teams"===e)return(0,t.jsx)("div",{className:"mt-2",children:z(p[e]||[])});if("user_role"===e&&a)return(0,t.jsx)(g.default,{style:{width:"100%"},value:p[e]||"",onChange:s=>I(e,s),className:"mt-2",children:Object.entries(a).filter(e=>{let[s]=e;return s.includes("internal_user")}).map(e=>{let[s,{ui_label:l,description:a}]=e;return(0,t.jsx)(w,{value:s,children:(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)("span",{children:l}),(0,t.jsx)("span",{className:"ml-2 text-xs text-gray-500",children:a})]})},s)})});if("budget_duration"===e)return(0,t.jsx)(k.Z,{value:p[e]||null,onChange:s=>I(e,s),className:"mt-2"});if("boolean"===r)return(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(K.Z,{checked:!!p[e],onChange:s=>I(e,s)})});if("array"===r&&(null===(i=s.items)||void 0===i?void 0:i.enum))return(0,t.jsx)(g.default,{mode:"multiple",style:{width:"100%"},value:p[e]||[],onChange:s=>I(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,t.jsx)(w,{value:e,children:e},e))});if("models"===e)return(0,t.jsxs)(g.default,{mode:"multiple",style:{width:"100%"},value:p[e]||[],onChange:s=>I(e,s),className:"mt-2",children:[(0,t.jsx)(w,{value:"no-default-models",children:"No Default Models"},"no-default-models"),(0,t.jsx)(w,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),b.map(e=>(0,t.jsx)(w,{value:e,children:(0,S.W0)(e)},e))]});if("string"===r&&s.enum)return(0,t.jsx)(g.default,{style:{width:"100%"},value:p[e]||"",onChange:s=>I(e,s),className:"mt-2",children:s.enum.map(e=>(0,t.jsx)(w,{value:e,children:e},e))});else return(0,t.jsx)(M.oi,{value:void 0!==p[e]?String(p[e]):"",onChange:s=>I(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},B=(e,s)=>{if(null==s)return(0,t.jsx)("span",{className:"text-gray-400",children:"Not set"});if("teams"===e&&Array.isArray(s)){if(0===s.length)return(0,t.jsx)("span",{className:"text-gray-400",children:"No teams assigned"});let e=D(s);return(0,t.jsx)("div",{className:"space-y-2 mt-1",children:e.map((e,s)=>(0,t.jsx)("div",{className:"border rounded-lg p-3 bg-white",children:(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"font-medium text-gray-600",children:"Team ID:"}),(0,t.jsx)("p",{className:"text-gray-900",children:e.team_id||"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"font-medium text-gray-600",children:"Max Budget:"}),(0,t.jsx)("p",{className:"text-gray-900",children:void 0!==e.max_budget_in_team?"$".concat((0,O.pw)(e.max_budget_in_team,4)):"No limit"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"font-medium text-gray-600",children:"Role:"}),(0,t.jsx)("p",{className:"text-gray-900 capitalize",children:e.user_role})]})]})},s))})}if("user_role"===e&&a&&a[s]){let{ui_label:e,description:l}=a[s];return(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"font-medium",children:e}),l&&(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:l})]})}return"budget_duration"===e?(0,t.jsx)("span",{children:(0,k.m)(s)}):"boolean"==typeof s?(0,t.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,t.jsx)("span",{className:"text-gray-400",children:"None"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:(0,S.W0)(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,t.jsx)("span",{className:"text-gray-400",children:"None"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,t.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,t.jsx)("span",{children:String(s)})};return o?(0,t.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,t.jsx)(V.Z,{size:"large"})}):u?(0,t.jsxs)(M.Zb,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(M.Dx,{children:"Default User Settings"}),!o&&u&&(x?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(M.zx,{variant:"secondary",onClick:()=>{h(!1),f(u.values||{})},disabled:y,children:"Cancel"}),(0,t.jsx)(M.zx,{onClick:C,loading:y,children:"Save Changes"})]}):(0,t.jsx)(M.zx,{onClick:()=>h(!0),children:"Edit Settings"}))]}),(null==u?void 0:null===(s=u.field_schema)||void 0===s?void 0:s.description)&&(0,t.jsx)(Z,{className:"mb-4",children:u.field_schema.description}),(0,t.jsx)(M.iz,{}),(0,t.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,field_schema:s}=u;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,a]=s,i=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,t.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,t.jsx)(M.xv,{className:"font-medium text-lg",children:r}),(0,t.jsx)(Z,{className:"text-sm text-gray-500 mt-1",children:a.description||"No description available"}),x?(0,t.jsx)("div",{className:"mt-2",children:A(l,a,i)}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:B(l,i)})]},l)}):(0,t.jsx)(M.xv,{children:"No schema information available"})})()})]}):(0,t.jsx)(M.Zb,{children:(0,t.jsx)(M.xv,{children:"No settings available or you do not have permission to view them."})})},Q=l(41649),H=l(67101),$=l(47323),W=l(15731),Y=l(53410),X=l(74998),ee=l(23628);let es=(e,s,l,a,i,r)=>{let n=[{header:"User ID",accessorKey:"user_id",enableSorting:!0,cell:e=>{let{row:s}=e;return(0,t.jsx)(f.Z,{title:s.original.user_id,children:(0,t.jsx)("span",{className:"text-xs",children:s.original.user_id?"".concat(s.original.user_id.slice(0,7),"..."):"-"})})}},{header:"Email",accessorKey:"user_email",enableSorting:!0,cell:e=>{let{row:s}=e;return(0,t.jsx)("span",{className:"text-xs",children:s.original.user_email||"-"})}},{header:"Global Proxy Role",accessorKey:"user_role",enableSorting:!0,cell:s=>{var l;let{row:a}=s;return(0,t.jsx)("span",{className:"text-xs",children:(null==e?void 0:null===(l=e[a.original.user_role])||void 0===l?void 0:l.ui_label)||"-"})}},{header:"User Alias",accessorKey:"user_alias",enableSorting:!1,cell:e=>{let{row:s}=e;return(0,t.jsx)("span",{className:"text-xs",children:s.original.user_alias||"-"})}},{header:"Spend (USD)",accessorKey:"spend",enableSorting:!0,cell:e=>{let{row:s}=e;return(0,t.jsx)("span",{className:"text-xs",children:s.original.spend?(0,O.pw)(s.original.spend,4):"-"})}},{header:"Budget (USD)",accessorKey:"max_budget",enableSorting:!1,cell:e=>{let{row:s}=e;return(0,t.jsx)("span",{className:"text-xs",children:null!==s.original.max_budget?s.original.max_budget:"Unlimited"})}},{header:()=>(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{children:"SSO ID"}),(0,t.jsx)(f.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,t.jsx)(W.Z,{className:"w-4 h-4"})})]}),accessorKey:"sso_user_id",enableSorting:!1,cell:e=>{let{row:s}=e;return(0,t.jsx)("span",{className:"text-xs",children:null!==s.original.sso_user_id?s.original.sso_user_id:"-"})}},{header:"Virtual Keys",accessorKey:"key_count",enableSorting:!1,cell:e=>{let{row:s}=e;return(0,t.jsx)(H.Z,{numItems:2,children:s.original.key_count>0?(0,t.jsxs)(Q.Z,{size:"xs",color:"indigo",children:[s.original.key_count," ",1===s.original.key_count?"Key":"Keys"]}):(0,t.jsx)(Q.Z,{size:"xs",color:"gray",children:"No Keys"})})}},{header:"Created At",accessorKey:"created_at",enableSorting:!0,cell:e=>{let{row:s}=e;return(0,t.jsx)("span",{className:"text-xs",children:s.original.created_at?new Date(s.original.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"updated_at",enableSorting:!1,cell:e=>{let{row:s}=e;return(0,t.jsx)("span",{className:"text-xs",children:s.original.updated_at?new Date(s.original.updated_at).toLocaleDateString():"-"})}},{id:"actions",header:"Actions",enableSorting:!1,cell:e=>{let{row:s}=e;return(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(f.Z,{title:"Edit user details",children:(0,t.jsx)($.Z,{icon:Y.Z,size:"sm",onClick:()=>i(s.original.user_id,!0),className:"cursor-pointer hover:text-blue-600"})}),(0,t.jsx)(f.Z,{title:"Delete user",children:(0,t.jsx)($.Z,{icon:X.Z,size:"sm",onClick:()=>l(s.original),className:"cursor-pointer hover:text-red-600"})}),(0,t.jsx)(f.Z,{title:"Reset Password",children:(0,t.jsx)($.Z,{icon:ee.Z,size:"sm",onClick:()=>a(s.original.user_id),className:"cursor-pointer hover:text-green-600"})})]})}}];if(r){let{onSelectUser:e,onSelectAll:s,isUserSelected:l,isAllSelected:a,isIndeterminate:i}=r;return[{id:"select",enableSorting:!1,header:()=>(0,t.jsx)(c.Z,{indeterminate:i,checked:a,onChange:e=>s(e.target.checked),onClick:e=>e.stopPropagation()}),cell:s=>{let{row:a}=s;return(0,t.jsx)(c.Z,{checked:l(a.original),onChange:s=>e(a.original,s.target.checked),onClick:e=>e.stopPropagation()})}},...n]}return n};var el=l(71594),et=l(24525),ea=l(27281),ei=l(21626),er=l(97214),en=l(28241),ed=l(58834),eo=l(69552),ec=l(71876),eu=l(44633),em=l(86462),ex=l(49084),eh=l(50337),eg=l(84717),ev=l(10900),ej=l(30401),ep=l(78867);function ef(e){var s,l,a,r,n,d,o,c,u,m,x,h,g,v,p,f,y,_,b,N,S,w,I,D,z,A,E,L,F,R,M,K,V,q,G,J,Q,H,$,W,Y,es,el,et,ea;let{userId:ei,onClose:er,accessToken:en,userRole:ed,onDelete:eo,possibleUIRoles:ec,initialTab:eu=0,startInEditMode:em=!1}=e,[ex,eh]=(0,i.useState)(null),[ef,ey]=(0,i.useState)(!1),[e_,eb]=(0,i.useState)(!1),[eN,eS]=(0,i.useState)(!0),[eZ,ew]=(0,i.useState)(em),[ek,eC]=(0,i.useState)([]),[eU,eI]=(0,i.useState)(!1),[eD,ez]=(0,i.useState)(null),[eA,eB]=(0,i.useState)(null),[eE,eT]=(0,i.useState)(eu),[eO,eL]=(0,i.useState)({}),[eF,eR]=(0,i.useState)(!1);i.useEffect(()=>{eB((0,j.getProxyBaseUrl)())},[]),i.useEffect(()=>{console.log("userId: ".concat(ei,", userRole: ").concat(ed,", accessToken: ").concat(en)),(async()=>{try{if(!en)return;let e=await (0,j.userInfoCall)(en,ei,ed||"",!1,null,null,!0);eh(e);let s=(await (0,j.modelAvailableCall)(en,ei,ed||"")).data.map(e=>e.id);eC(s)}catch(e){console.error("Error fetching user data:",e),U.Z.fromBackend("Failed to fetch user data")}finally{eS(!1)}})()},[en,ei,ed]);let eP=async()=>{if(!en){U.Z.fromBackend("Access token not found");return}try{U.Z.success("Generating password reset link...");let e=await (0,j.invitationCreateCall)(en,ei);ez(e),eI(!0)}catch(e){U.Z.fromBackend("Failed to generate password reset link")}},eM=async()=>{try{if(!en)return;eb(!0),await (0,j.userDeleteCall)(en,[ei]),U.Z.success("User deleted successfully"),eo&&eo(),er()}catch(e){console.error("Error deleting user:",e),U.Z.fromBackend("Failed to delete user")}finally{ey(!1),eb(!1)}},eK=async e=>{try{if(!en||!ex)return;await (0,j.userUpdateUserCall)(en,e,null),eh({...ex,user_info:{...ex.user_info,user_email:e.user_email,user_alias:e.user_alias,models:e.models,max_budget:e.max_budget,budget_duration:e.budget_duration,metadata:e.metadata}}),U.Z.success("User updated successfully"),ew(!1)}catch(e){console.error("Error updating user:",e),U.Z.fromBackend("Failed to update user")}};if(eN)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(eg.zx,{icon:ev.Z,variant:"light",onClick:er,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(eg.xv,{children:"Loading user data..."})]});if(!ex)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(eg.zx,{icon:ev.Z,variant:"light",onClick:er,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(eg.xv,{children:"User not found"})]});let eV=async(e,s)=>{await (0,O.vQ)(e)&&(eL(e=>({...e,[s]:!0})),setTimeout(()=>{eL(e=>({...e,[s]:!1}))},2e3))};return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.zx,{icon:ev.Z,variant:"light",onClick:er,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(eg.Dx,{children:(null===(s=ex.user_info)||void 0===s?void 0:s.user_email)||"User"}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(eg.xv,{className:"text-gray-500 font-mono",children:ex.user_id}),(0,t.jsx)(B.ZP,{type:"text",size:"small",icon:eO["user-id"]?(0,t.jsx)(ej.Z,{size:12}):(0,t.jsx)(ep.Z,{size:12}),onClick:()=>eV(ex.user_id,"user-id"),className:"left-2 z-10 transition-all duration-200 ".concat(eO["user-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100")})]})]}),ed&&Z.LQ.includes(ed)&&(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(eg.zx,{icon:ee.Z,variant:"secondary",onClick:eP,className:"flex items-center",children:"Reset Password"}),(0,t.jsx)(eg.zx,{icon:X.Z,variant:"secondary",onClick:()=>ey(!0),className:"flex items-center text-red-500 border-red-500 hover:text-red-600 hover:border-red-600",children:"Delete User"})]})]}),(0,t.jsx)(P.Z,{isOpen:ef,title:"Delete User?",message:"Are you sure you want to delete this user? This action cannot be undone.",resourceInformationTitle:"User Information",resourceInformation:[{label:"Email",value:null===(l=ex.user_info)||void 0===l?void 0:l.user_email},{label:"User ID",value:ex.user_id,code:!0},{label:"Global Proxy Role",value:(null===(a=ex.user_info)||void 0===a?void 0:a.user_role)&&(null==ec?void 0:null===(r=ec[ex.user_info.user_role])||void 0===r?void 0:r.ui_label)||(null===(n=ex.user_info)||void 0===n?void 0:n.user_role)||"-"},{label:"Total Spend (USD)",value:(null===(d=ex.user_info)||void 0===d?void 0:d.spend)!==null&&(null===(o=ex.user_info)||void 0===o?void 0:o.spend)!==void 0?ex.user_info.spend.toFixed(2):void 0}],onCancel:()=>{ey(!1)},onOk:eM,confirmLoading:e_}),(0,t.jsxs)(eg.v0,{defaultIndex:eE,onIndexChange:eT,children:[(0,t.jsxs)(eg.td,{className:"mb-4",children:[(0,t.jsx)(eg.OK,{children:"Overview"}),(0,t.jsx)(eg.OK,{children:"Details"})]}),(0,t.jsxs)(eg.nP,{children:[(0,t.jsx)(eg.x4,{children:(0,t.jsxs)(eg.rj,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(eg.Zb,{children:[(0,t.jsx)(eg.xv,{children:"Spend"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(eg.Dx,{children:["$",(0,O.pw)((null===(c=ex.user_info)||void 0===c?void 0:c.spend)||0,4)]}),(0,t.jsxs)(eg.xv,{children:["of"," ",(null===(u=ex.user_info)||void 0===u?void 0:u.max_budget)!==null?"$".concat((0,O.pw)(ex.user_info.max_budget,4)):"Unlimited"]})]})]}),(0,t.jsxs)(eg.Zb,{children:[(0,t.jsx)(eg.xv,{children:"Teams"}),(0,t.jsx)("div",{className:"mt-2",children:(null===(m=ex.teams)||void 0===m?void 0:m.length)&&(null===(x=ex.teams)||void 0===x?void 0:x.length)>0?(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[null===(h=ex.teams)||void 0===h?void 0:h.slice(0,eF?ex.teams.length:20).map((e,s)=>(0,t.jsx)(eg.Ct,{color:"blue",title:e.team_alias,children:e.team_alias},s)),!eF&&(null===(g=ex.teams)||void 0===g?void 0:g.length)>20&&(0,t.jsxs)(eg.Ct,{color:"gray",className:"cursor-pointer hover:bg-gray-200 transition-colors",onClick:()=>eR(!0),children:["+",ex.teams.length-20," more"]}),eF&&(null===(v=ex.teams)||void 0===v?void 0:v.length)>20&&(0,t.jsx)(eg.Ct,{color:"gray",className:"cursor-pointer hover:bg-gray-200 transition-colors",onClick:()=>eR(!1),children:"Show Less"})]}):(0,t.jsx)(eg.xv,{children:"No teams"})})]}),(0,t.jsxs)(eg.Zb,{children:[(0,t.jsx)(eg.xv,{children:"Virtual Keys"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsxs)(eg.xv,{children:[(null===(p=ex.keys)||void 0===p?void 0:p.length)||0," ",(null===(f=ex.keys)||void 0===f?void 0:f.length)===1?"Key":"Keys"]})})]}),(0,t.jsxs)(eg.Zb,{children:[(0,t.jsx)(eg.xv,{children:"Personal Models"}),(0,t.jsx)("div",{className:"mt-2",children:(null===(_=ex.user_info)||void 0===_?void 0:null===(y=_.models)||void 0===y?void 0:y.length)&&(null===(N=ex.user_info)||void 0===N?void 0:null===(b=N.models)||void 0===b?void 0:b.length)>0?null===(w=ex.user_info)||void 0===w?void 0:null===(S=w.models)||void 0===S?void 0:S.map((e,s)=>(0,t.jsx)(eg.xv,{children:e},s)):(0,t.jsx)(eg.xv,{children:"All proxy models"})})]})]})}),(0,t.jsx)(eg.x4,{children:(0,t.jsxs)(eg.Zb,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(eg.Dx,{children:"User Settings"}),!eZ&&ed&&Z.LQ.includes(ed)&&(0,t.jsx)(eg.zx,{onClick:()=>ew(!0),children:"Edit Settings"})]}),eZ&&ex?(0,t.jsx)(C,{userData:ex,onCancel:()=>ew(!1),onSubmit:eK,teams:ex.teams,accessToken:en,userID:ei,userRole:ed,userModels:ek,possibleUIRoles:ec}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"User ID"}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(eg.xv,{className:"font-mono",children:ex.user_id}),(0,t.jsx)(B.ZP,{type:"text",size:"small",icon:eO["user-id"]?(0,t.jsx)(ej.Z,{size:12}):(0,t.jsx)(ep.Z,{size:12}),onClick:()=>eV(ex.user_id,"user-id"),className:"left-2 z-10 transition-all duration-200 ".concat(eO["user-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100")})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Email"}),(0,t.jsx)(eg.xv,{children:(null===(I=ex.user_info)||void 0===I?void 0:I.user_email)||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"User Alias"}),(0,t.jsx)(eg.xv,{children:(null===(D=ex.user_info)||void 0===D?void 0:D.user_alias)||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Global Proxy Role"}),(0,t.jsx)(eg.xv,{children:(null===(z=ex.user_info)||void 0===z?void 0:z.user_role)||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Created"}),(0,t.jsx)(eg.xv,{children:(null===(A=ex.user_info)||void 0===A?void 0:A.created_at)?new Date(ex.user_info.created_at).toLocaleString():"Unknown"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Last Updated"}),(0,t.jsx)(eg.xv,{children:(null===(E=ex.user_info)||void 0===E?void 0:E.updated_at)?new Date(ex.user_info.updated_at).toLocaleString():"Unknown"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Teams"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(L=ex.teams)||void 0===L?void 0:L.length)&&(null===(F=ex.teams)||void 0===F?void 0:F.length)>0?(0,t.jsxs)(t.Fragment,{children:[null===(R=ex.teams)||void 0===R?void 0:R.slice(0,eF?ex.teams.length:20).map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",title:e.team_alias||e.team_id,children:e.team_alias||e.team_id},s)),!eF&&(null===(M=ex.teams)||void 0===M?void 0:M.length)>20&&(0,t.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded text-xs cursor-pointer hover:bg-gray-200 transition-colors",onClick:()=>eR(!0),children:["+",ex.teams.length-20," more"]}),eF&&(null===(K=ex.teams)||void 0===K?void 0:K.length)>20&&(0,t.jsx)("span",{className:"px-2 py-1 bg-gray-100 rounded text-xs cursor-pointer hover:bg-gray-200 transition-colors",onClick:()=>eR(!1),children:"Show Less"})]}):(0,t.jsx)(eg.xv,{children:"No teams"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Personal Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(q=ex.user_info)||void 0===q?void 0:null===(V=q.models)||void 0===V?void 0:V.length)&&(null===(J=ex.user_info)||void 0===J?void 0:null===(G=J.models)||void 0===G?void 0:G.length)>0?null===(H=ex.user_info)||void 0===H?void 0:null===(Q=H.models)||void 0===Q?void 0:Q.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):(0,t.jsx)(eg.xv,{children:"All proxy models"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Virtual Keys"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===($=ex.keys)||void 0===$?void 0:$.length)&&(null===(W=ex.keys)||void 0===W?void 0:W.length)>0?ex.keys.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-green-100 rounded text-xs",children:e.key_alias||e.token},s)):(0,t.jsx)(eg.xv,{children:"No Virtual Keys"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Max Budget"}),(0,t.jsx)(eg.xv,{children:(null===(Y=ex.user_info)||void 0===Y?void 0:Y.max_budget)!==null&&(null===(es=ex.user_info)||void 0===es?void 0:es.max_budget)!==void 0?"$".concat((0,O.pw)(ex.user_info.max_budget,4)):"Unlimited"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Budget Reset"}),(0,t.jsx)(eg.xv,{children:(0,k.m)(null!==(ea=null===(el=ex.user_info)||void 0===el?void 0:el.budget_duration)&&void 0!==ea?ea:null)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg.xv,{className:"font-medium",children:"Metadata"}),(0,t.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify((null===(et=ex.user_info)||void 0===et?void 0:et.metadata)||{},null,2)})]})]})]})})]})]}),(0,t.jsx)(T.Z,{isInvitationLinkModalVisible:eU,setIsInvitationLinkModalVisible:eI,baseUrl:eA||"",invitationLinkData:eD,modalType:"resetPassword"})]})}var ey=l(56083),e_=l(51205),eb=l(57716),eN=l(73247),eS=l(92369),eZ=l(66344);function ew(e){let{data:s=[],columns:l,isLoading:a=!1,onSortChange:r,currentSort:n,accessToken:d,userRole:o,possibleUIRoles:c,handleEdit:u,handleDelete:m,handleResetPassword:x,selectedUsers:h=[],onSelectionChange:g,enableSelection:v=!1,filters:j,updateFilters:p,initialFilters:f,teams:y,userListResponse:b,currentPage:N,handlePageChange:S}=e,[Z,w]=i.useState([{id:(null==n?void 0:n.sortBy)||"created_at",desc:(null==n?void 0:n.sortOrder)==="desc"}]),[k,C]=i.useState(null),[U,I]=i.useState(!1),[D,z]=i.useState(!1),A=function(e){let s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];C(e),I(s)},B=(e,s)=>{g&&(s?g([...h,e]):g(h.filter(s=>s.user_id!==e.user_id)))},E=e=>{g&&(e?g(s):g([]))},T=e=>h.some(s=>s.user_id===e.user_id),O=s.length>0&&h.length===s.length,L=h.length>0&&h.lengthc?es(c,u,m,x,A,v?{selectedUsers:h,onSelectUser:B,onSelectAll:E,isUserSelected:T,isAllSelected:O,isIndeterminate:L}:void 0):l,[c,u,m,x,A,l,v,h,O,L]),R=(0,el.b7)({data:s,columns:F,state:{sorting:Z},onSortingChange:e=>{let s="function"==typeof e?e(Z):e;if(w(s),s&&Array.isArray(s)&&s.length>0&&s[0]){let e=s[0];if(e.id){let s=e.id,l=e.desc?"desc":"asc";null==r||r(s,l)}}else null==r||r("created_at","desc")},getCoreRowModel:(0,et.sC)(),manualSorting:!0,enableSorting:!0});return(i.useEffect(()=>{n&&w([{id:n.sortBy,desc:"desc"===n.sortOrder}])},[n]),k)?(0,t.jsx)(ef,{userId:k,onClose:()=>{C(null),I(!1)},accessToken:d,userRole:o,possibleUIRoles:c,initialTab:U?1:0,startInEditMode:U}):(0,t.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,t.jsx)("div",{className:"border-b px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsx)(ey.H,{placeholder:"Search by email...",value:j.email,onChange:e=>p({email:e}),icon:eN.Z}),(0,t.jsx)(e_.c,{onClick:()=>z(!D),active:D,hasActiveFilters:!!(j.user_id||j.user_role||j.team)}),(0,t.jsx)(eb.z,{onClick:()=>{p(f)}})]}),D&&(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,t.jsx)(ey.H,{placeholder:"Filter by User ID",value:j.user_id,onChange:e=>p({user_id:e}),icon:eS.Z}),(0,t.jsx)(ey.H,{placeholder:"Filter by SSO ID",value:j.sso_user_id,onChange:e=>p({sso_user_id:e}),icon:eZ.Z}),(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(ea.Z,{value:j.user_role,onValueChange:e=>p({user_role:e}),placeholder:"Select Role",children:c&&Object.entries(c).map(e=>{let[s,l]=e;return(0,t.jsx)(_.Z,{value:s,children:l.ui_label},s)})})}),(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(ea.Z,{value:j.team,onValueChange:e=>p({team:e}),placeholder:"Select Team",children:null==y?void 0:y.map(e=>(0,t.jsx)(_.Z,{value:e.team_id,children:e.team_alias||e.team_id},e.team_id))})})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[a?(0,t.jsx)(eh.Z.Input,{active:!0,style:{width:192,height:20}}):(0,t.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",b&&b.users&&b.users.length>0?(b.page-1)*b.page_size+1:0," ","-"," ",b&&b.users?Math.min(b.page*b.page_size,b.total):0," ","of ",b?b.total:0," results"]}),(0,t.jsx)("div",{className:"flex space-x-2",children:a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eh.Z.Button,{active:!0,size:"small",style:{width:80,height:30}}),(0,t.jsx)(eh.Z.Button,{active:!0,size:"small",style:{width:60,height:30}})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{onClick:()=>S(N-1),disabled:1===N,className:"px-3 py-1 text-sm border rounded-md ".concat(1===N?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Previous"}),(0,t.jsx)("button",{onClick:()=>S(N+1),disabled:!b||N>=b.total_pages,className:"px-3 py-1 text-sm border rounded-md ".concat(!b||N>=b.total_pages?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Next"})]})})]})]})}),(0,t.jsx)("div",{className:"overflow-auto",children:(0,t.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(ei.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(ed.Z,{children:R.getHeaderGroups().map(e=>(0,t.jsx)(ec.Z,{children:e.headers.map(e=>(0,t.jsx)(eo.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)]":""," ").concat(e.column.getCanSort()?"cursor-pointer hover:bg-gray-50":""),onClick:e.column.getToggleSortingHandler(),children:(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,el.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&e.column.getCanSort()&&(0,t.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,t.jsx)(eu.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(em.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(ex.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,t.jsx)(er.Z,{children:a?(0,t.jsx)(ec.Z,{children:(0,t.jsx)(en.Z,{colSpan:F.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"\uD83D\uDE85 Loading users..."})})})}):s.length>0?R.getRowModel().rows.map(e=>(0,t.jsx)(ec.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,t.jsx)(en.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&&A(e.getValue(),!1)},style:{cursor:"user_id"===e.column.id?"pointer":"default",color:"user_id"===e.column.id?"#3b82f6":"inherit"},children:(0,el.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(ec.Z,{children:(0,t.jsx)(en.Z,{colSpan:F.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No users found"})})})})})]})})})})]})}let{Text:ek,Title:eC}=n.default,eU={email:"",user_id:"",user_role:"",sso_user_id:"",team:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"};var eI=e=>{var s,l,n;let{accessToken:d,token:o,userRole:c,userID:u,teams:m}=e,x=(0,F.NL)(),[h,g]=(0,i.useState)(1),[v,p]=(0,i.useState)(!1),[f,y]=(0,i.useState)(null),[_,b]=(0,i.useState)(!1),[N,S]=(0,i.useState)(!1),[w,k]=(0,i.useState)(null),[C,I]=(0,i.useState)("users"),[D,B]=(0,i.useState)(eU),[M,K,V]=(0,L.G)(D,{wait:300}),[q,G]=(0,i.useState)(!1),[Q,H]=(0,i.useState)(null),[$,W]=(0,i.useState)(null),[Y,X]=(0,i.useState)([]),[ee,el]=(0,i.useState)(!1),[et,ea]=(0,i.useState)(!1),[ei,er]=(0,i.useState)([]),en=e=>{k(e),b(!0)};(0,i.useEffect)(()=>()=>{V.cancel()},[V]),(0,i.useEffect)(()=>{W((0,j.getProxyBaseUrl)())},[]),(0,i.useEffect)(()=>{(async()=>{try{if(!u||!c||!d)return;let e=(await (0,j.modelAvailableCall)(d,u,c)).data.map(e=>e.id);console.log("available_model_names:",e),er(e)}catch(e){console.error("Error fetching user models:",e)}})()},[d,u,c]);let ed=e=>{B(s=>{let l={...s,...e};return K(l),l})},eo=async e=>{if(!d){U.Z.fromBackend("Access token not found");return}try{U.Z.success("Generating password reset link...");let s=await (0,j.invitationCreateCall)(d,e);H(s),G(!0)}catch(e){U.Z.fromBackend("Failed to generate password reset link")}},ec=async()=>{if(w&&d)try{S(!0),await (0,j.userDeleteCall)(d,[w.user_id]),x.setQueriesData({queryKey:["userList"]},e=>{if(void 0===e)return e;let s=e.users.filter(e=>e.user_id!==w.user_id);return{...e,users:s}}),U.Z.success("User deleted successfully")}catch(e){console.error("Error deleting user:",e),U.Z.fromBackend("Failed to delete user")}finally{b(!1),k(null),S(!1)}},eu=async()=>{y(null),p(!1)},em=async e=>{if(console.log("inside handleEditSubmit:",e),d&&o&&c&&u){try{let s=await (0,j.userUpdateUserCall)(d,e,null);x.setQueriesData({queryKey:["userList"]},e=>{if(void 0===e)return e;let l=e.users.map(e=>e.user_id===s.data.user_id?(0,O.nl)(e,s.data):e);return{...e,users:l}}),U.Z.success("User ".concat(e.user_id," updated successfully"))}catch(e){console.error("There was an error updating the user",e)}y(null),p(!1)}},ex=async e=>{g(e)},eg=(0,R.a)({queryKey:["userList",{debouncedFilter:M,currentPage:h}],queryFn:async()=>{if(!d)throw Error("Access token required");return await (0,j.userListCall)(d,M.user_id?[M.user_id]:null,h,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order)},enabled:!!(d&&o&&c&&u),placeholderData:e=>e}),ev=eg.data,ej=(0,R.a)({queryKey:["userRoles"],initialData:()=>({}),queryFn:async()=>{if(!d)throw Error("Access token required");return await (0,j.getPossibleUserRoles)(d)},enabled:!!(d&&o&&c&&u)}).data,ep=es(ej,e=>{y(e),p(!0)},en,eo,()=>{});return(0,t.jsxs)("div",{className:"w-full p-8 overflow-hidden",children:[(0,t.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,t.jsx)("div",{className:"flex space-x-3",children:eg.isLoading?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eh.Z.Button,{active:!0,size:"default",shape:"default",style:{width:110,height:36}}),(0,t.jsx)(eh.Z.Button,{active:!0,size:"default",shape:"default",style:{width:145,height:36}}),(0,t.jsx)(eh.Z.Button,{active:!0,size:"default",shape:"default",style:{width:110,height:36}})]}):u&&d?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(A.Z,{userID:u,accessToken:d,teams:m,possibleUIRoles:ej}),(0,t.jsx)(r.z,{onClick:()=>{ea(!et),X([])},variant:et?"primary":"secondary",className:"flex items-center",children:et?"Cancel Selection":"Select Users"}),et&&(0,t.jsxs)(r.z,{onClick:()=>{if(0===Y.length){U.Z.fromBackend("Please select users to edit");return}el(!0)},disabled:0===Y.length,className:"flex items-center",children:["Bulk Edit (",Y.length," selected)"]})]}):null})}),(0,t.jsxs)(a.v0,{defaultIndex:0,onIndexChange:e=>I(0===e?"users":"settings"),children:[(0,t.jsxs)(a.td,{className:"mb-4",children:[(0,t.jsx)(a.OK,{children:"Users"}),(0,t.jsx)(a.OK,{children:"Default User Settings"})]}),(0,t.jsxs)(a.nP,{children:[(0,t.jsx)(a.x4,{children:(0,t.jsx)(ew,{data:(null===(s=eg.data)||void 0===s?void 0:s.users)||[],columns:ep,isLoading:eg.isLoading,accessToken:d,userRole:c,onSortChange:(e,s)=>{ed({sort_by:e,sort_order:s})},currentSort:{sortBy:D.sort_by,sortOrder:D.sort_order},possibleUIRoles:ej,handleEdit:e=>{y(e),p(!0)},handleDelete:en,handleResetPassword:eo,enableSelection:et,selectedUsers:Y,onSelectionChange:e=>{X(e)},filters:D,updateFilters:ed,initialFilters:eU,teams:m,userListResponse:ev,currentPage:h,handlePageChange:ex})}),(0,t.jsx)(a.x4,{children:u&&c&&d?(0,t.jsx)(J,{accessToken:d,possibleUIRoles:ej,userID:u,userRole:c}):(0,t.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,t.jsx)(eh.Z,{active:!0,paragraph:{rows:4}})})})]})]}),(0,t.jsx)(E,{visible:v,possibleUIRoles:ej,onCancel:eu,user:f,onSubmit:em}),(0,t.jsx)(P.Z,{isOpen:_,title:"Delete User?",message:"Are you sure you want to delete this user? This action cannot be undone.",resourceInformationTitle:"User Information",resourceInformation:[{label:"Email",value:null==w?void 0:w.user_email},{label:"User ID",value:null==w?void 0:w.user_id,code:!0},{label:"Global Proxy Role",value:w&&(null==ej?void 0:null===(l=ej[w.user_role])||void 0===l?void 0:l.ui_label)||(null==w?void 0:w.user_role)||"-"},{label:"Total Spend (USD)",value:null==w?void 0:null===(n=w.spend)||void 0===n?void 0:n.toFixed(2)}],onCancel:()=>{b(!1),k(null)},onOk:ec,confirmLoading:N}),(0,t.jsx)(T.Z,{isInvitationLinkModalVisible:q,setIsInvitationLinkModalVisible:G,baseUrl:$||"",invitationLinkData:Q,modalType:"resetPassword"}),(0,t.jsx)(z,{open:ee,onCancel:()=>el(!1),selectedUsers:Y,possibleUIRoles:ej,accessToken:d,onSuccess:()=>{x.invalidateQueries({queryKey:["userList"]}),X([]),ea(!1)},teams:m,userRole:c,userModels:ei,allowAllUsers:!!c&&(0,Z.tY)(c)})]})}}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/2353-c94748c0aac514ff.js b/litellm/proxy/_experimental/out/_next/static/chunks/2353-c94748c0aac514ff.js deleted file mode 100644 index 3426c548b25..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/2353-c94748c0aac514ff.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2353],{57365:function(e,t,n){n.d(t,{Z:function(){return a}});var r=n(5853),o=n(2265),l=n(51975),i=n(13241);let u=(0,n(1153).fn)("SelectItem"),a=o.forwardRef((e,t)=>{let{value:n,icon:a,className:s,children:c}=e,d=(0,r._T)(e,["value","icon","className","children"]);return o.createElement(l.wt,Object.assign({className:(0,i.q)(u("root"),"flex justify-start items-center cursor-default text-tremor-default px-2.5 py-2.5","data-[focus]:bg-tremor-background-muted data-[focus]:text-tremor-content-strong data-[selected]:text-tremor-content-strong data-[selected]:bg-tremor-background-muted text-tremor-content-emphasis","dark:data-[focus]:bg-dark-tremor-background-muted dark:data-[focus]:text-dark-tremor-content-strong dark:data-[selected]:text-dark-tremor-content-strong dark:data-[selected]:bg-dark-tremor-background-muted dark:text-dark-tremor-content-emphasis",s),ref:t,key:n,value:n},d),a&&o.createElement(a,{className:(0,i.q)(u("icon"),"flex-none w-5 h-5 mr-1.5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")}),o.createElement("span",{className:"whitespace-nowrap truncate"},null!=c?c:n))});a.displayName="SelectItem"},44140:function(e,t,n){n.d(t,{Z:function(){return o}});var r=n(2265);let o=(e,t)=>{let n=void 0!==t,[o,l]=(0,r.useState)(e);return[n?t:o,e=>{n||l(e)}]}},64803:function(e,t,n){n.d(t,{RR:function(){return v},YF:function(){return d},cv:function(){return f},dp:function(){return m},uY:function(){return p}});var r=n(51050),o=n(2265),l=n(54887),i="undefined"!=typeof document?o.useLayoutEffect:function(){};function u(e,t){let n,r,o;if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if((n=e.length)!==t.length)return!1;for(r=n;0!=r--;)if(!u(e[r],t[r]))return!1;return!0}if((n=(o=Object.keys(e)).length)!==Object.keys(t).length)return!1;for(r=n;0!=r--;)if(!({}).hasOwnProperty.call(t,o[r]))return!1;for(r=n;0!=r--;){let n=o[r];if(("_owner"!==n||!e.$$typeof)&&!u(e[n],t[n]))return!1}return!0}return e!=e&&t!=t}function a(e){return"undefined"==typeof window?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function s(e,t){let n=a(e);return Math.round(t*n)/n}function c(e){let t=o.useRef(e);return i(()=>{t.current=e}),t}function d(e){void 0===e&&(e={});let{placement:t="bottom",strategy:n="absolute",middleware:d=[],platform:f,elements:{reference:p,floating:v}={},transform:m=!0,whileElementsMounted:g,open:h}=e,[b,x]=o.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[E,y]=o.useState(d);u(E,d)||y(d);let[S,O]=o.useState(null),[R,w]=o.useState(null),C=o.useCallback(e=>{e!==k.current&&(k.current=e,O(e))},[]),P=o.useCallback(e=>{e!==M.current&&(M.current=e,w(e))},[]),L=p||S,T=v||R,k=o.useRef(null),M=o.useRef(null),I=o.useRef(b),F=null!=g,A=c(g),D=c(f),N=c(h),z=o.useCallback(()=>{if(!k.current||!M.current)return;let e={placement:t,strategy:n,middleware:E};D.current&&(e.platform=D.current),(0,r.oo)(k.current,M.current,e).then(e=>{let t={...e,isPositioned:!1!==N.current};H.current&&!u(I.current,t)&&(I.current=t,l.flushSync(()=>{x(t)}))})},[E,t,n,D,N]);i(()=>{!1===h&&I.current.isPositioned&&(I.current.isPositioned=!1,x(e=>({...e,isPositioned:!1})))},[h]);let H=o.useRef(!1);i(()=>(H.current=!0,()=>{H.current=!1}),[]),i(()=>{if(L&&(k.current=L),T&&(M.current=T),L&&T){if(A.current)return A.current(L,T,z);z()}},[L,T,z,A,F]);let _=o.useMemo(()=>({reference:k,floating:M,setReference:C,setFloating:P}),[C,P]),B=o.useMemo(()=>({reference:L,floating:T}),[L,T]),V=o.useMemo(()=>{let e={position:n,left:0,top:0};if(!B.floating)return e;let t=s(B.floating,b.x),r=s(B.floating,b.y);return m?{...e,transform:"translate("+t+"px, "+r+"px)",...a(B.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:t,top:r}},[n,m,B.floating,b.x,b.y]);return o.useMemo(()=>({...b,update:z,refs:_,elements:B,floatingStyles:V}),[b,z,_,B,V])}let f=(e,t)=>({...(0,r.cv)(e),options:[e,t]}),p=(e,t)=>({...(0,r.uY)(e),options:[e,t]}),v=(e,t)=>({...(0,r.RR)(e),options:[e,t]}),m=(e,t)=>({...(0,r.dp)(e),options:[e,t]})},52307:function(e,t,n){n.d(t,{dk:function(){return f},fw:function(){return d},zH:function(){return c}});var r=n(2265),o=n(93980),l=n(73389),i=n(67561),u=n(87550),a=n(38929);let s=(0,r.createContext)(null);function c(){var e,t;return null!=(t=null==(e=(0,r.useContext)(s))?void 0:e.value)?t:void 0}function d(){let[e,t]=(0,r.useState)([]);return[e.length>0?e.join(" "):void 0,(0,r.useMemo)(()=>function(e){let n=(0,o.z)(e=>(t(t=>[...t,e]),()=>t(t=>{let n=t.slice(),r=n.indexOf(e);return -1!==r&&n.splice(r,1),n}))),l=(0,r.useMemo)(()=>({register:n,slot:e.slot,name:e.name,props:e.props,value:e.value}),[n,e.slot,e.name,e.props,e.value]);return r.createElement(s.Provider,{value:l},e.children)},[t])]}s.displayName="DescriptionContext";let f=Object.assign((0,a.yV)(function(e,t){let n=(0,r.useId)(),o=(0,u.B)(),{id:c="headlessui-description-".concat(n),...d}=e,f=function e(){let t=(0,r.useContext)(s);if(null===t){let t=Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(t,e),t}return t}(),p=(0,i.T)(t);(0,l.e)(()=>f.register(c),[c,f.register]);let v=o||!1,m=(0,r.useMemo)(()=>({...f.slot,disabled:v}),[f.slot,v]),g={ref:p,...f.props,id:c};return(0,a.L6)()({ourProps:g,theirProps:d,slot:m,defaultTag:"p",name:f.name||"Description"})}),{})},7935:function(e,t,n){n.d(t,{__:function(){return p},bE:function(){return f},wp:function(){return d}});var r=n(2265),o=n(93980),l=n(73389),i=n(67561),u=n(87550),a=n(80281),s=n(38929);let c=(0,r.createContext)(null);function d(e){var t,n,o;let l=null!=(n=null==(t=(0,r.useContext)(c))?void 0:t.value)?n:void 0;return(null!=(o=null==e?void 0:e.length)?o:0)>0?[l,...e].filter(Boolean).join(" "):l}function f(){let{inherit:e=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=d(),[n,l]=(0,r.useState)([]),i=e?[t,...n].filter(Boolean):n;return[i.length>0?i.join(" "):void 0,(0,r.useMemo)(()=>function(e){let t=(0,o.z)(e=>(l(t=>[...t,e]),()=>l(t=>{let n=t.slice(),r=n.indexOf(e);return -1!==r&&n.splice(r,1),n}))),n=(0,r.useMemo)(()=>({register:t,slot:e.slot,name:e.name,props:e.props,value:e.value}),[t,e.slot,e.name,e.props,e.value]);return r.createElement(c.Provider,{value:n},e.children)},[l])]}c.displayName="LabelContext";let p=Object.assign((0,s.yV)(function(e,t){var n;let d=(0,r.useId)(),f=function e(){let t=(0,r.useContext)(c);if(null===t){let t=Error("You used a